android图片拼,Android 拼接图片

我只实现是纵向拼接,当然要实现各种各样的拼接道理都是一样的。

需要注意的是,图片路径中,最后一个字符是“#”的表示该图片需要进行顺时针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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值