解決了OOM的問題

來源:互聯網
上載者:User

標籤:public   return   false   圖片   

public class ImageUtils

{


/**

* 從SDCard讀取圖片時壓縮

* 

* @param srcPath

* @return

*/

public static Bitmap compressImageFromFile(String srcPath,

float ww, float hh )

{

BitmapFactory.Options newOpts = new BitmapFactory.Options();

newOpts.inJustDecodeBounds = true;// 唯讀邊,不讀內容

Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);


newOpts.inJustDecodeBounds = false;

int w = newOpts.outWidth;

int h = newOpts.outHeight;

//float hh = 800f;//

//float ww = 480f;//

int be = 1;

// 縮放到可以在480x800的螢幕上完整顯示圖片

if (w >= h && w >= ww)

{

be = (int) (newOpts.outWidth / ww);

} else if (w < h && h > hh)

{

be = (int) (newOpts.outHeight / hh);

}

if (be <= 0)

be = 1;

newOpts.inSampleSize = be;// 設定採樣率


newOpts.inPreferredConfig = Config.ARGB_8888;// 該模式是預設的,可不設

newOpts.inPurgeable = true;// 同時設定才會有效

newOpts.inInputShareable = true;// 。當系統記憶體不夠時候圖片自動被回收


bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

return bitmap;

}


/**

* 將圖片在記憶體中壓縮

* 

* @param image

* @return

*/

public static Bitmap compressBmpFromBmp(Bitmap image)

{

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int options = 100;

image.compress(Bitmap.CompressFormat.JPEG, 100, baos);

// 壓縮到剛好小於100kb為止

while (baos.toByteArray().length / 1024 > 100)

{

baos.reset();

options -= 10;

image.compress(Bitmap.CompressFormat.JPEG, options, baos);

}

ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());

Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);

return bitmap;

}

}


本文出自 “android技術” 部落格,請務必保留此出處http://340431827.blog.51cto.com/9096201/1533220

聯繫我們

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