android compress 壓縮 會不會失真

微信的縮略圖要求是不大於32k,這就需要對我的圖片進行壓縮。試了幾種方法,一一道來。

  代碼如下

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
  int options = 100 ;
  while ( baos.toByteArray().length / 1024 > 32 ) {
  baos.reset();
  image.compress(Bitmap.CompressFormat.JPEG, options, baos);
  options -= 10 ;
  }
  ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
  Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null );
  最開始使用這個來進行壓縮,但是始終壓縮不到32k這麼小。後來看高手的解釋才明白,這種壓縮方法之所以稱之爲質量壓縮,是因爲它不會減少圖片的像素。它是在保持像素的前提下改變圖片的位深及透明度等,來達到壓縮圖片的目的。進過它壓縮的圖片文件大小會有改變,但是導入成bitmap後佔得內存是不變的。因爲要保持像素不變,所以它就無法無限壓縮,到達一個值之後就不會繼續變小了。顯然這個方法並不適用與縮略圖,其實也不適用於想通過壓縮圖片減少內存的適用,僅僅適用於想在保證圖片質量的同時減少文件大小的情況而已。
  2、採樣率壓縮法:

  代碼如下

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.JPEG, 100, out);
  BitmapFactory.Options newOpts = new BitmapFactory.Options();
  int be = 2;
  newOpts.inSampleSize = be;
  ByteArrayInputStream isBm = new ByteArrayInputStream(out.toByteArray());
  Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null );
  第二個使用的是這個方法,可以將圖片壓縮到足夠小,但是也有一些問題。因爲採樣率是整數,所以不能很好的保證圖片的質量。如我們需要的是在2和3採樣率之間,用2的話圖片就大了一點,但是用3的話圖片質量就會有很明顯的下降。這樣也無法完全滿足我的需要。不過這個方法的好處是大大的縮小了內存的使用,在讀存儲器上的圖片時,如果不需要高清的效果,可以先只讀取圖片的邊,通過寬和高設定好取樣率後再加載圖片,這樣就不會過多的佔用內存。如下

  BitmapFactory.Options newOpts = new BitmapFactory.Options();
  newOpts.inJustDecodeBounds = true ;
  Bitmap bitmap = BitmapFactory.decodeFile(path,newOpts);
  newOpts.inJustDecodeBounds = false ;
  int w = newOpts.outWidth;
  int h = newOpts.outHeight;
  //計算出取樣率
  newOpts.inSampleSize = be;
  bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
  這樣的好處是不會先將大圖片讀入內存,大大減少了內存的使用,也不必考慮將大圖片讀入內存後的釋放事宜。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章