天天看点

图片极致压缩,不失真

在各种项目中,都难免遇到图片的上传和下载,然而,图片的上传,需要压缩后再上传才是明智之举;然后,压缩图片可能会导致图片的失真等等问题,在这里,我将在工作中使用的比较好的图片压缩方法,分享给大家。

public static Bitmap revitionImage(String path) throws IOException {

BufferedInputStream in = new BufferedInputStream(new FileInputStream(

new File(path)));

BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeStream(in, null, options);

int height = options.outHeight;

int width = options.outWidth;

int inSampleSize = 1;

int reqHeight = 800;

int reqWidth = 480;

if (height > reqHeight || width > reqHeight) {

final int heightRatio = Math.round((float) height / (float) reqHeight);

final int widthRatio = Math.round((float) width / (float) reqWidth);

inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

}

options.inJustDecodeBounds = false;

options.inSampleSize = inSampleSize;

Bitmap bitmap = BitmapFactory.decodeFile(path, options);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);

byte[] b = baos.toByteArray();

Bitmap result = BitmapFactory.decodeByteArray(b, 0, b.length);

if (baos != null)

baos.close();

if (in != null)

in.close();

return result;

}

继续阅读