/**
* 根据路径压缩图片上传
* @param path
* @param imageSize
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap
compressImage(String path,
int imageSize,
int reqWidth,
int reqHeight) {
Bitmap bitmaps=getSmallBitmaped(path,reqWidth,reqHeight);
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
bitmaps.compress(Bitmap.CompressFormat.JPEG,
100, baos);
int options =
100;
while ( baos.toByteArray().length /
1024>imageSize) {
baos.reset();
bitmaps.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -=
10;
}
ByteArrayInputStream isBm =
new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm,
null,
null);
return bitmap;
}
/**
* 根据路径获得图片并压缩尺寸,返回bitmap用于显示
*/
public static Bitmap
getSmallBitmaped(String path,
int reqWidth,
int reqHeight) {
final BitmapFactory.Options options =
new BitmapFactory.Options();
options.inJustDecodeBounds =
true;
BitmapFactory.decodeFile(path,options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds =
false;
return BitmapFactory.decodeFile(path,options);
}
/**
* 计算图片的缩放值
*/
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;
}
转载请注明原文地址: https://ju.6miu.com/read-2602.html