Android(java)學習筆記236:多媒體之載入大圖片到記憶體(Bitmap API)

來源:互聯網
上載者:User

標籤:

1.Bitmap (API使用)

android裡面的bitmap中,一個像素點需要4個byte去表示,這是因為android表示顏色是" argb ";其中 a 表示是透明度,然後是" rgb"

顏色表示範圍 00000000 ~~~ffffffff

2.載入圖片到記憶體:

上面說到了圖形表示使用4byte,和int一樣,所以Android裡面每個像素點都是使用一個int來表示的。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.girl);
iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bitmap);

 

 

2.載入大圖片到記憶體:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_phone);
iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bitmap);

這裡的圖片very_large_phone非常大,1.69M(2560*1504);

那麼這個圖片在Android中需要2560*1504*4 = 15400960 byte才能表示這張圖片,結果或出現OOM(OUT OF MEMONY)記憶體溢出的錯誤。

說明Android顯示圖片不是看圖片自身的大小,而是看解析度。

 

 

那麼Android該怎麼顯示大圖片(大解析度)?

 

//為了避免oom異常,根據螢幕的尺寸對圖片進行縮放

//1.先擷取手機螢幕的寬和高

WindowManager  wm = (WindowManager)getSystemService( WINDOW_SERVICE );

int  screenWidth  =  wm.getDefaultDisplay().getWidth();

int  screenHeight = wm.getDefaultDisplay().getHeight();

 

//2.擷取圖片的寬和高

BitmapFactory.Options  opts = new Option();//建立一個配置參數

opts.inJustDecodeBounds = true;//表示不真實地解析這個位元影像,只是解析位元影像的寬高資訊(不申請空間解析這個圖片,自然沒有記憶體溢出)

 

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_phone,opts);

int  width = opts.outWidth ;

int  height = opts.outHeight ;

 

//3.計算縮放的比例

int scale = 1;

int scaleX = width  / screenWidth;

int scaleY = height / screenHeight;

if(scaleX > scaleY && scaleY >1 ) {

     scale = scaleX ;

}

if(scaleY> scaleX && scaleX  >1 ) {

               scale = scaleY ;

}

 

//4.根據縮放比例,真實解析位元影像

opts.inSampleSize = scale;

opts.inJustDecodeBounds = false;//真實地解析這個位元影像,返回bitmap;

 bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_phone,opts);//縮放後的bitmap

iv.setImageBitmap(bitmap);

 

Android(java)學習筆記236:多媒體之載入大圖片到記憶體(Bitmap API)

聯繫我們

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