Android應用開發中咱們會常常用到圖片處理的技術,今天給你們分享些獲取固定寬度圖片的技巧 測試
移動開發中,內存資源很寶貴,並且對加載圖片內存空間也有限制;因此咱們會在加載圖片對圖片進行相應的處理,有時爲了提升響應速度,加強用戶體驗,咱們在加載大圖片時會先加載圖片的縮略圖、如後加載原圖,因此咱們要將圖片按照固定大小取縮略圖,通常取縮略圖的方法是使用BitmapFactory的decodeFile方法,而後經過傳遞進去 BitmapFactory.Option類型的參數進行取縮略圖,在Option中,屬性值inSampleSize表示縮略圖大小爲原始圖片大小的幾分之一,即若是這個值爲2,則取出的縮略圖的寬和高都是原始圖片的1/2,圖片大小就爲原始大小的1/4。 this
然而,若是咱們想取固定大小的縮略圖就比較困難了,好比,咱們想將不一樣大小的圖片去出來的縮略圖高度都爲200px,並且要保證圖片不失真,那怎麼辦?咱們總不能將原始圖片加載到內存中再進行縮放處理吧,要知道在移動開發中,內存是至關寶貴的,並且一張100K的圖片,加載完所佔用的內存何止 100K?
通過研究,發現,Options中有個屬性inJustDecodeBounds,研究了一下,終於明白是什麼意思了,SDK中的E文是這麼說的
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
意思就是說若是該值設爲true那麼將不返回實際的bitmap不給其分配內存空間而裏面只包括一些解碼邊界信息即圖片大小信息,那麼相應的方法也就出來了,經過設置inJustDecodeBounds爲true,獲取到outHeight(圖片原始高度)和 outWidth(圖片的原始寬度),而後計算一個inSampleSize(縮放值),而後就能夠取圖片了,這裏要注意的是,inSampleSize 可能小於0,必須作判斷。
具體代碼以下: spa
FrameLayout fr=(FrameLayout)findViewById(R.id.FrameLayout01);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 獲取這個圖片的寬和高
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg", options); //此時返回bm爲空
options.inJustDecodeBounds = false;
//計算縮放比
int be = (int)(options.outHeight / (float)200);
if (be <= 0)
be = 1;
options.inSampleSize = be;
//從新讀入圖片,注意此次要把options.inJustDecodeBounds 設爲 false哦
bitmap=BitmapFactory.decodeFile("/sdcard/test.jpg",options);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
System.out.println(w+" "+h);
ImageView iv=new ImageView(this);
iv.setImageBitmap(bitmap);
這樣咱們就能夠讀取較大的圖片就會避免內存溢出了。若是你想把壓縮後的圖片保存在Sdcard上的話就很簡單了:
File file=new File("/sdcard/feng.png");
try {
FileOutputStream out=new FileOutputStream(file);
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ok,這樣就把圖片保存在/sdcard/feng.png這個文件裏面了 code
下面是我通過測試對比出來的圖片效果 orm