Android 之 圖片壓縮

來源:互聯網
上載者:User

標籤:

在上一篇文章中(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 之 圖片壓縮

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.