Sunday, May 22, 2011

Combine two images in android java


In this blog we are combine two images and we have two images stored locally on an SD card or drawble folder in android.

Steps:

Read the image from Source
InputStream istream = context.getResources().openRawResource(R.drawable.img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(R.drawable.img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}

Define the Image property
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}

Create your target Bitmap,
Bitmap combinedImages = Bitmap.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);

Create a Canvas for it,
Canvas comboImage = new Canvas(combinedImages);
Use Canvas.drawBitmap to blit each source bitmap into your target bitmap
comboImage.drawBitmap(image1, 0f, 0f, null);
comboImage.drawBitmap(image2, 0f, image1.getHeight()+1, null);

Example:
public Bitmap combineImages(Context context, int img1, int img2) {
// Bitmap[] mBitmap = new Bitmap[6];
Bitmap image1, image2;

InputStream istream = context.getResources().openRawResource(img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Bitmap combinedImages = null;
combinedImages = Bitmap
.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(combinedImages);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight()+1, null);
return cs;
}

No comments:

Post a Comment