我只实现是纵向拼接,当然要实现各种各样的拼接道理都是一样的。
需要注意的是,图片路径中,最后一个字符是“#”的表示该图片需要进行顺时针90°的翻转,用于纠正手机竖着拍照时照片方向不对。
拼接操作比较耗时,建议放进线程中操作,否则图片一多容易发生ANR。
/**
* @param context 上下文
* @param photoPaths 图片路径数组
* @param newWidth 限制宽度
* @return 拼接后图片路径
* @throws IOException
*/
public static String pieceTogetherPhotos(Context context, ArrayList photoPaths, int newWidth) throws IOException {
ArrayList bmps = new ArrayList();
int taotalHeight = 0; //总高度,用与创建拼接后的bitmap
//压缩图片
for (String path : photoPaths) {
boolean rotate = false;
if (path.charAt(path.length() - 1) == '#') { //竖拍
rotate = true;
path = path.substring(0, path.length() - 1);
}
Bitmap bm = BitmapFactory.decodeFile(path);
//获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
//缩放比例
float scale = (float)newWidth / (float)width;
//取得想要缩放的matrix参数
Matrix matrix = new Matrix();
//如果是竖拍先不压缩
if (!rotate) {
matrix.postScale(scale, scale);
}
//是竖拍先翻转
if (rotate) {
matrix.postRotate(90);
}
Bitmap newBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
//竖拍需要先翻转后再压缩
if (rotate) {
width = newBitmap.getWidth();
height = newBitmap.getHeight();
scale = (float)newWidth / (float)width;
matrix = new Matrix();
matrix.postScale(scale, scale);
newBitmap = Bitmap.createBitmap(newBitmap, 0, 0, width, height, matrix, true);
}
bmps.add(newBitmap);
taotalHeight += newBitmap.getHeight();
}
//拼接图片
Bitmap longBmp = Bitmap.createBitmap(newWidth, taotalHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(longBmp); //构造画布
float currentHeight = 0.0f; //记录最终的高度
for (Bitmap bm : bmps) {
canvas.drawBitmap(bm, 0.0f, currentHeight, null); //主要方法,在画布某个位置画上图像
currentHeight += bm.getHeight();
}
//保存图片
String fileName = "temp.jpg";
FileOutputStream fos;
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
longBmp.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
//返回图片文件绝对路径
return context.getFilesDir().getAbsolutePath() + "/" + fileName;
}