拼接两张图片分为两种情况,两者宽度相同和两者宽度不同
两者宽度相同
//创建一个两张图片高度相加的bitmap对象
Bitmap retBmp = Bitmap.createBitmap(width, bitmapFirst.getHeight() + bitmapSecond.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(retBmp);
//依次绘制两张图片至对应bitmap对象
canvas.drawBitmap(bitmapFirst, 0, 0, null);
canvas.drawBitmap(bitmapSecond, 0, bitmapFirst.getHeight(), null);
两者宽度不相同
//获取两张图片的宽度比
int h2 = bitmapSecond.getHeight() * width / bitmapSecond.getWidth();
Bitmap retBmp = Bitmap.createBitmap(width, bitmapFirst.getHeight() + h2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(retBmp);
//以第一张图片的宽度为基准对第二张图片的宽度和高度进行缩放
Bitmap newSizeBmp2 = resizeBitmap(bitmapSecond, width, h2);
//依次绘制两张图片
canvas.drawBitmap(bitmapFirst, 0, 0, null);
canvas.drawBitmap(newSizeBmp2, 0, bitmapFirst.getHeight(), null);
缩放操作
public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
float scaleWidth = ((float) newWidth) / bitmap.getWidth();
float scaleHeight = ((float) newHeight) / bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bmpScale = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return bmpScale;
}
附上整个代码:
public class CombineImage {
//将两张图片合成一张
public static Bitmap doCombineTask(Bitmap bitmapFirst, Bitmap bitmapSecond){
Bitmap retBmp;
int width = bitmapFirst.getWidth();
if (bitmapSecond.getWidth() != width) {
//以第一张图片的宽度为标准,对第二张图片进行缩放。
int h2 = bitmapSecond.getHeight() * width / bitmapSecond.getWidth();
retBmp = Bitmap.createBitmap(width, bitmapFirst.getHeight() + h2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(retBmp);
Bitmap newSizeBmp2 = resizeBitmap(bitmapSecond, width, h2);
canvas.drawBitmap(bitmapFirst, 0, 0, null);
canvas.drawBitmap(newSizeBmp2, 0, bitmapFirst.getHeight(), null);
} else {
//两张图片宽度相等,则直接拼接。
retBmp = Bitmap.createBitmap(width, bitmapFirst.getHeight() + bitmapSecond.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(retBmp);
canvas.drawBitmap(bitmapFirst, 0, 0, null);
canvas.drawBitmap(bitmapSecond, 0, bitmapFirst.getHeight(), null);
}
return retBmp;
}
public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
float scaleWidth = ((float) newWidth) / bitmap.getWidth();
float scaleHeight = ((float) newHeight) / bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bmpScale = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return bmpScale;
}
}