LGImageCompressor.java
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(srcImagePath, options);
//根据原始图片的宽高比和期望的输出图片的宽高比计算最终输出的图片的宽和高
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
float maxWidth = outWidth;//期望输出的图片宽度
float maxHeight = outHeight;//期望输出的图片高度
float srcRatio = srcWidth / srcHeight;
float outRatio = maxWidth / maxHeight;
float actualOutWidth = srcWidth;//最终输出的图片宽度
float actualOutHeight = srcHeight;//最终输出的图片高度
if (srcWidth > maxWidth || srcHeight > maxHeight) {
if (srcRatio < outRatio) {
actualOutHeight = maxHeight;
actualOutWidth = actualOutHeight * srcRatio;
} else if (srcRatio > outRatio) {
actualOutWidth = maxWidth;
actualOutHeight = actualOutWidth / srcRatio;
} else {
actualOutWidth = maxWidth;
actualOutHeight = maxHeight;
}
}
//计算sampleSize
options.inSampleSize = computSampleSize(options, actualOutWidth, actualOutHeight);
public boolean compress(CompressFormat format, int quality, OutputStream stream)
//进行有损压缩
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options_ = 100;
actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, options_, baos);//质量压缩方法,把压缩后的数据存放到baos中 (100表示不压缩,0表示压缩到最小)
int baosLength = baos.toByteArray().length;
while (baosLength / 1024 > maxFileSize) {//循环判断如果压缩后图片是否大于maxMemmorrySize,大于继续压缩
baos.reset();//重置baos即让下一次的写入覆盖之前的内容
options_ = Math.max(0, options_ - 10);//图片质量每次减少10
actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, options_, baos);//将压缩后的图片保存到baos中
baosLength = baos.toByteArray().length;
if (options_ == 0)//如果图片的质量已降到最低则,不再进行压缩
break;
}
private class CompressTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
return compressImage();//执行压缩操作
}
@Override
protected void onPreExecute() {
if (compressListener != null) {
compressListener.onCompressStart();//监听回调(开始压缩)
}
}
@Override
protected void onPostExecute(String imageOutPath) {
if (compressListener != null) {
compressListener.onCompressEnd(imageOutPath);//监听回调(压缩结束)
}
}
}
LGImgCompressor.getInstance(this).withListener(this).starCompress(Uri.fromFile(imageFile).toString(),outWidth,outHeight,maxFileSize);
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有