Android 拼接图片

来源:互联网 发布:云计算架构工程师招聘 编辑:程序博客网 时间:2024/06/03 01:58

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

需要注意的是,图片路径中,最后一个字符是“#”的表示该图片需要进行顺时针90°的翻转,用于纠正手机竖着拍照时照片方向不对。

拼接操作比较耗时,建议放进线程中操作,否则图片一多容易发生ANR。

/** * @param context 上下文 * @param photoPaths 图片路径数组 * @param newWidth 限制宽度 * @return 拼接后图片路径 * @throws IOException */public static String pieceTogetherPhotos(Context context, ArrayList<String> photoPaths, int newWidth) throws IOException {ArrayList<Bitmap> bmps = new ArrayList<Bitmap>();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 0
原创粉丝点击