圖片壓縮演算法,保證圖片不失真
阿新 • • 發佈:2019-01-25
在各種專案中,都難免遇到圖片的上傳和下載,然而,圖片的上傳,需要壓縮後再上傳才是明智之舉;然後,壓縮圖片可能會導致圖片的失真等等問題,在這裡,我將在工作中使用的比較好的圖片壓縮方法,分享給大家。
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);
<span style="white-space: pre;"> </span> 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; }