Android中對原始圖片的縮放

我們知道在圖片在網絡上傳的時候如果圖片過大,則對整體流量和資源的佔用都比較厲害甚至出現oom內存溢出所以在上傳的時候或者僅僅是對sd卡內部圖片的預覽時均需要進行縮放具體的代碼如下:可以按比例縮小也可以按一定的規則進行變化,lru方法調用這個類後在進行算法的優化來如內存爲10兆當裝滿後再來圖片則去掉最後的item這樣就可以最大程度的保障手機內存的加載圖片的優越性

public class BitmapUtilities {

 public BitmapUtilities() {
  // TODO Auto-generated constructor stub
 }
 
 public static Bitmap getBitmapThumbnail(String path,int width,int height){
  Bitmap bitmap = null;
  //這裏可以按比例縮小圖片:
  /*BitmapFactory.Options opts = new BitmapFactory.Options();
  opts.inSampleSize = 4;//寬和高都是原來的1/4
  bitmap = BitmapFactory.decodeFile(path, opts); */
  
  /*進一步的,
             如何設置恰當的inSampleSize是解決該問題的關鍵之一。BitmapFactory.Options提供了另一個成員inJustDecodeBounds。
            設置inJustDecodeBounds爲true後,decodeFile並不分配空間,但可計算出原始圖片的長度和寬度,即opts.width和opts.height。
            有了這兩個參數,再通過一定的算法,即可得到一個恰當的inSampleSize。*/
  BitmapFactory.Options opts = new BitmapFactory.Options();
     opts.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(path, opts);
     opts.inSampleSize = Math.max((int)(opts.outHeight / (float) height), (int)(opts.outWidth / (float) width));
     opts.inJustDecodeBounds = false;
     bitmap = BitmapFactory.decodeFile(path, opts);
  return bitmap;
 }
 
 public static Bitmap getBitmapThumbnail(Bitmap bmp,int width,int height){
  Bitmap bitmap = null;
  if(bmp != null ){
   //原始圖片的寬度和高度
   int bmpWidth = bmp.getWidth();
   int bmpHeight = bmp.getHeight();
   if(width != 0 && height !=0){
    Matrix matrix = new Matrix();
    float scaleWidth = ((float) width / bmpWidth);
    float scaleHeight = ((float) height / bmpHeight);
    matrix.postScale(scaleWidth, scaleHeight);
    bitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true);
   }else{
    bitmap = bmp;
   }
  }
  return bitmap;
 }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章