Android開發之大位元影像二次採樣壓縮處理(原始碼分享)

來源:互聯網
上載者:User

標籤:android   記憶體泄露   bitmap   壓縮   位元影像   

          圖片有各種形狀和大小。在許多情況下這些圖片是遠遠大於我們的使用者介面(UI)且佔據著極大的記憶體空間,如果我們不對位元影像進行壓縮處理,我們的程式會發生記憶體泄露的錯誤。

MainActivity的代碼

package com.example.g08_bitmap;import android.os.Bundle;import android.app.Activity;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.widget.ImageView;public class MainActivity extends Activity {private ImageView imageView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) this.findViewById(R.id.imageView1);imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.drawable.a, 300, 300));}public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();//先將inJustDecodeBounds屬性設定為true,解碼避免記憶體配置options.inJustDecodeBounds = true;// 將圖片傳入選取器中BitmapFactory.decodeResource(res, resId, options);// 對圖片進行指定比例的壓縮options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);//待圖片處理完成後再進行記憶體的分配,避免記憶體泄露的發生options.inJustDecodeBounds = false;return BitmapFactory.decodeResource(res, resId, options);}// 計算圖片的壓縮比例public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {// Raw height and width of imagefinal 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;}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.