/**
* 图片压缩的帮助类型,可以参考的工具类
*
* @author jerrydong
* @since 2023/5/23
*/
public class ImageCompressUtils {
private static final String TAG = "ImageCompressUtils";
// Jpg的压缩比,可以根据需求修改
private static final int QUALITY_DEFAULT = 85;
/**
* 主动压缩YUV图片的算法
*
* @param image 待压缩的图片
* @return
*/
public static byte[] doCompressYuvImage(YuvImage image) {
int dataWidth = image.getWidth();
int dataHeight = image.getHeight();
try (ByteArrayOutputStream outputSteam = new ByteArrayOutputStream()) {
image.compressToJpeg(new Rect(0, 0, dataWidth, dataHeight), QUALITY_DEFAULT, outputSteam);
// 转BitMap并压缩
Options options = new BitmapFactory.Options();
// 不使用透明通道
options.inPreferredConfig = Config.RGB_565;
// 修改图片的采样率
options.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeByteArray(outputSteam.toByteArray(), 0, outputSteam.size(), options);
outputSteam.reset();
// 主动压缩图片
bmp.compress(CompressFormat.JPEG, QUALITY_DEFAULT, outputSteam);
return outputSteam.toByteArray();
} catch (IOException e) {
Log.e(TAG, "Compress error");
}
return null;
}
/**
* 主动压缩BitMap
*
* @param inputMap
* @return
*/
public Bitmap doCompressBitMap(Bitmap inputMap) {
try (ByteArrayOutputStream outputSteam = new ByteArrayOutputStream()) {
inputMap.compress(CompressFormat.JPEG, QUALITY_DEFAULT, outputSteam);
// 转BitMap并压缩(可以写通用方法!)
Options options = new BitmapFactory.Options();
// 不使用透明通道
options.inPreferredConfig = Config.RGB_565;
// 修改图片的采样率(可以根据实际情况计算)
options.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeByteArray(outputSteam.toByteArray(), 0, outputSteam.size(), options);
outputSteam.reset();
return bmp;
} catch (IOException e) {
Log.e(TAG, "Compress error");
}
return null;
}
/**
* 缩放方法进行缩放
*
* @param inputMap
* @param scale 缩放大小
* @return
*/
public Bitmap matrixBitmap(Bitmap inputMap, float scale) {
// 根据旋转角度,生成旋转矩阵
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(inputMap, 0, 0, inputMap.getWidth(), inputMap.getHeight(), matrix, true);
return bitmap;
}
}