Android 按指定大小讀取圖片的實例
在Android開發(fā)中,我們經(jīng)常遇到Android讀取圖片大小超過屏幕顯示的圖(一般只要顯示一定規(guī)格的預(yù)覽圖即可),在圖片特別多或者圖片顯示很頻繁的時候要特別注意這個問題,下面介紹個按指定大小讀取圖像的方法。
實現(xiàn)原理:首先獲取圖片文件的圖像高和寬,如果小于指定比例,則直接讀??;如果超過比例則按指定比例壓縮讀取。
捕獲OutOfMemoryError時注意點:后面返回的是null,不要馬上從別的地方再讀圖片,包括R文件中的,不然依然會拋出這個異常,一般在初始化的時候緩存默認(rèn)圖片,然后顯示緩存中的圖片。
/** 獲取圖像的寬高**/
public static int[] getImageWH(String path) {
int[] wh = {-1, -1};
if (path == null) {
return wh;
}
File file = new File(path);
if (file.exists() && !file.isDirectory()) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream is = new FileInputStream(path);
BitmapFactory.decodeStream(is, null, options);
wh[0] = options.outWidth;
wh[1] = options.outHeight;
}
catch (Exception e) {
Log.w(TAG, "getImageWH Exception.", e);
}
}
return wh;
}
public static Bitmap createBitmapByScale(String path, int scale) {
Bitmap bm = null;
try {
//獲取寬高
int[] wh = getImageWH(path);
if (wh[0] == -1 || wh[1] == -1) {
return null;
}
//讀取圖片
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = Math.max(wh[0]/scale, wh[1]/scale);
InputStream is = new FileInputStream(path);
bm = BitmapFactory.decodeStream(is, null, options);
}
catch (Exception e) {
Log.w(TAG, "createBitmapByScale Exception.", e);
}
catch (OutOfMemoryError e) {
Log.w(TAG, "createBitmapByScale OutOfMemoryError.", e);
//TODO: out of memory deal..
}
return bm;
}
以上就是解決Android 讀取圖片大小顯示的問題,有需要的朋友可以參考下。
相關(guān)文章
Android?RxJava與Retrofit結(jié)合使用詳解
RxJava和Retrofit的結(jié)合使用估計已經(jīng)相當(dāng)普遍了,自己工作中也是一直都在使用。在使用的過程中我們都會對其進(jìn)行封裝使用,GitHub上也有很多封裝好的項目可以直接拿來使用,其實對于開源框架的二次封裝有時候針對不同的業(yè)務(wù)邏輯封裝的過程中也多多少少有些不同2023-03-03
Assert.assertEquals()方法參數(shù)詳解
本文詳細(xì)講解了Assert.assertEquals()方法參數(shù),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12
Android Intent 用法全面總結(jié)及實例代碼
這篇文章主要介紹了Android Intent 用法全面總結(jié)的相關(guān)資料,并附實例代碼,需要的朋友可以參考下2016-09-09
Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法
android 讀取json數(shù)據(jù),下面小編給大家整理有關(guān)Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法,需要的朋友可以參考下2015-08-08

