在各種項目中,都難免遇到圖檔的上傳和下載下傳,然而,圖檔的上傳,需要壓縮後再上傳才是明智之舉;然後,壓縮圖檔可能會導緻圖檔的失真等等問題,在這裡,我将在工作中使用的比較好的圖檔壓縮方法,分享給大家。
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;
}