Android 開發圖片壓縮/縮圖的方法

來源:互聯網
上載者:User

Android 開發圖片壓縮/縮圖的方法

在開發圖片瀏覽器等軟體是,很多時候要顯示圖片的縮圖,而一般情況下,我們要將圖片按照固定大小取縮圖,一般取縮圖的方法是使用BitmapFactory的decodeFile方法,然後通過傳遞進去 BitmapFactory.Option類型的參數進行取縮圖,在Option中,屬性值inSampleSize表示縮圖大小為原始圖片大小的幾 分之一,即如果這個值為2,則取出的縮圖的寬和高都是原始圖片的1/2,圖片大小就為原始大小的1/4。然而,如果我們想取固定大小的縮圖就比較困難了,比如,我們想將不同大小的圖片去出來的縮圖高度都為200px,而且要保證圖片不失真,那怎麼辦?我 們總不能將原始圖片載入到記憶體中再進行縮放處理吧,要知道在移動開發中,記憶體是相當寶貴的,而且一張100K的圖片,載入完所佔用的記憶體何止 100K?我們發現,Options中有個屬性inJustDecodeBounds,SDK中的英文引用如下: If set totrue, the decoder will return null (no bitmap), but the out... fields will stillbe set, allowing the caller to query the bitmap without having to allocate thememory for its pixels.意思就是說如果該值設為true那麼將不返回實際的bitmap不給其分配記憶體空間而裡面只包括一些解碼邊界資訊即圖片大小資訊,那麼相應的方法也就出來 了,通過設定inJustDecodeBounds為true,擷取到outHeight(圖片原始高度)和 outWidth(圖片的原始寬度),然後計算一個inSampleSize(縮放值),然後就可以取圖片了,這裡要注意的是,inSampleSize 可能小於0,必須做判斷。具體代碼如下:

 
01 FrameLayout fr=(FrameLayout)findViewById(R.id.FrameLayout01);
02 BitmapFactory.Options options =new
BitmapFactory.Options();
03 options.inJustDecodeBounds =true;
04 // 擷取這個圖片的寬和高
05 Bitmap bitmap =BitmapFactory.decodeFile("/sdcard/test.jpg", options);
//此時返回bm為空白
06 options.inJustDecodeBounds =false;
07 //計算縮放比
08 int be = (int)(options.outHeight/ (float)200);
09 if
(be <= 0)
10 be = 1;
11 options.inSampleSize = be;
12 //重新讀入圖片,注意這次要把options.inJustDecodeBounds 設為 false哦
13 bitmap=BitmapFactory.decodeFile("/sdcard/test.jpg",options);
14 int w = bitmap.getWidth();
15 int h = bitmap.getHeight();
16 System.out.println(w+" "+h);
17 ImageView iv=new
ImageView(this);
18 iv.setImageBitmap(bitmap);

這樣我們就可以讀取較大的圖片而不會記憶體溢出了。如果你想把壓縮後的圖片儲存在Sdcard上的話就很簡單了:

01 File file=new
File("/sdcard/feng.png");
02 try
{
03 FileOutputStream out=newFileOutputStream(file);
04 if(bitmap.compress(Bitmap.CompressFormat.PNG,
100, out)){
05 out.flush();
06 out.close();
07 }
08 }
catch (FileNotFoundException e){
09 // TODO Auto-generated catchblock
10 e.printStackTrace();
11 }
catch (IOException e) {
12 // TODO Auto-generated catchblock
13 e.printStackTrace();
14 }

實現上述操作,就可將圖片儲存在/sdcard/feng.png這個檔案裡面了! 

 
相關文章

聯繫我們

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