@Tyhj
2017-02-24T17:24:05.000000Z
字数 1429
阅读 1477
Android
原文:https://www.zybuluo.com/Tyhj/note/666195
Android中,图片展示的时候可以用各种框架,图片工具来很好的展示。但是涉及到图片上传的时候,比如上传头像什么的,我们就可以先将图片压缩一下再上传。
//计算图片的缩放值
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
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;
}
return inSampleSize;
}
//图片压缩
public static void ImgCompress(String filePath,File newFile,int IMAGE_SIZE) {
//图片质量百分比
int imageMg=100;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
//规定要压缩图片的分辨率
options.inSampleSize = calculateInSampleSize(options,1080,1920);
options.inJustDecodeBounds = false;
Bitmap bitmap= BitmapFactory.decodeFile(filePath, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, imageMg, baos);
//如果文件大于100KB就进行质量压缩,每次压缩比例增加百分之五
while (baos.toByteArray().length / 1024 > IMAGE_SIZE&&imageMg>60){
baos.reset();
imageMg-=5;
bitmap.compress(Bitmap.CompressFormat.JPEG, imageMg, baos);
}
//然后输出到指定的文件中
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newFile);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
}