android图片压缩(分辨率压缩和质量压缩)

您所在的位置:网站首页 安卓图片压缩app android图片压缩(分辨率压缩和质量压缩)

android图片压缩(分辨率压缩和质量压缩)

2023-12-15 02:07| 来源: 网络整理| 查看: 265

需求:对于大于1M的图片,先进行分辨率压缩,将短边压缩为1224,如果仍然大于1M(非png图片)再进行质量压缩

分辨率压缩:

int degree = readPictureDegree(fromFile);//获取相片拍摄角度 int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); // 缩放图片的尺寸 if (bitmapWidth > bitmapHeight) { width = (int) (height * bitmapWidth / bitmapHeight); } else { height = (int) (width * bitmapHeight / bitmapWidth); } float scaleWidth = (float) width / bitmapWidth; float scaleHeight = (float) height / bitmapHeight; Matrix matrix = new Matrix(); if (degree != 0) { matrix.postRotate(degree);// 设置拍摄角度 } matrix.postScale(scaleWidth, scaleHeight); // 产生缩放后的Bitmap对象 resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);

质量压缩:

Bitmap bitmap = null; ByteArrayInputStream isBm = null; image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 while (baos.toByteArray().length > maxSize) { // 循环判断如果压缩后图片是否大于1m,大于继续压缩 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10;// 每次都减少10 } byte[] bytes = baos.toByteArray(); bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap;

源码下载地址为:https://download.csdn.net/download/qq_26149467/10306062

工具类上的注解会报错,直接删掉就好。

调用:

String compressImage = pictureUtil.transImage(path, 1224, 1224, 70, 1024 * 1024 * 1); java.io.File compressedPic = new java.io.File(compressImage); if (compressedPic.exists()) { uploadPic(compressImage, index); } else {//直接上传 uploadPic(path, index); }


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3