先压缩到指定尺寸,再压缩到指定大小
/**
* 计算图片的缩放值* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
Log.d(TAG ,"source height=" + height + " width=" + width);
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
Log.d(TAG ,"inSampleSize=" + inSampleSize);
return inSampleSize;
}
/**
* 按质量压缩
* @param image
* @return
*/
public static void compressImageByQuality(Bitmap image, String outPath) throws Exception{
File file = new File(outPath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 90;
while (baos.toByteArray().length > (1024L * 100L)) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;
if(options < 0){
break;
}
}
if(file.exists()){
file.delete();
}
file.createNewFile();
FileOutputStream os = new FileOutputStream(file);
os.write(baos.toByteArray());
os.close();
}
/**
* 从文件压缩
* @param srcPath
* @return
*/
public static void compressImageFromFile(String srcPath, String outPath, int reqWidth, int reqHight) throws Exception{
Log.d(TAG , "srcPath=" + srcPath + "\n outPath=" + outPath + "\n reqWidth=" + reqWidth + " reqHight=" + reqHight);
try {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;//只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inSampleSize = calculateInSampleSize(newOpts, reqWidth, reqHight);
newOpts.inJustDecodeBounds = false;
newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;//当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
compressImageByQuality(bitmap, outPath);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Image compress error, by " + e.getMessage());
}
}
图片压缩技巧
本文介绍了一种图片压缩的方法,包括如何按指定尺寸缩放图片及如何通过调整图片质量来进一步减小文件大小。此方法适用于需要优化图片占用空间的应用场景。
1059

被折叠的 条评论
为什么被折叠?



