標籤:
在上一篇文章中(Android之圖片變換)主要說明了bitmap的使用,當然其中也包括一點圖片壓縮的內容,但是沒有詳細描述,這篇文章就來闡述一下平時Android使用的圖片壓縮技術
從圖片的壓縮方式區分:品質壓縮和尺寸壓縮。
品質壓縮是在保持像素的前提下改變圖片的位深及透明度等,來達到壓縮圖片的目的,經過它壓縮的圖片檔案大小會有改變,但是匯入成bitmap後佔得記憶體是不變的。因為要保持像素不變,所以它就無法無限壓縮,到達一個值之後就不會繼續變小了。顯然這個方法並不適用與縮圖,其實也不適用於想通過壓縮圖片減少記憶體的適用,僅僅適用於想在保證圖片品質的同時減少檔案大小的情況而已
尺寸壓縮是壓縮圖片的像素,一張圖片所佔記憶體的大小 圖片類型*寬*高,通過改變三個值減小圖片所佔的記憶體,防止OOM,當然這種方式可能會使圖片失真
品質壓縮:
public Bitmap compressImage(Bitmap image,int imageSize) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//品質壓縮方法,這裡100表示不壓縮,把壓縮後的資料存放到baos中 int options = 100; while ( baos.toByteArray().length / 1024>imageSize) { //迴圈判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮 baos.reset();//重設baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裡壓縮options%,把壓縮後的資料存放到baos中 options -= 10;//每次都減少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮後的資料baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream資料產生圖片 return bitmap; }
尺寸壓縮:
public void scalePic(int reqWidth,int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options); options.inSampleSize = PhotoUtil.calculateInSampleSize(options, reqWidth,reqHeight); options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options); postInvalidate(); }
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; }
根據具體需求也可以兩種壓縮方式結合使用
Android 之 圖片壓縮