BitmapFactory.Options.inSampleSize 的使用方法


  • BitmapFactory.decodeFile(imageFile);

    用BitmapFactory解碼一張圖片時。有時會遇到該錯誤。

    這往往是因為圖片過大造成的。

    要想正常使用,則須要分配更少的內存空間來存儲。

    BitmapFactory.Options.inSampleSize

    設置恰當的inSampleSize能夠使BitmapFactory分配更少的空間以消除該錯誤。inSampleSize的詳細含義請參考SDK文檔。

    比如:

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 4;
    Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);

    設置恰當的inSampleSize是解決該問題的關鍵之中的一個。BitmapFactory.Options提供了還有一個成員inJustDecodeBounds。

    BitmapFactory.Options opts = new BitmapFactory.Options();
    
    opts.inJustDecodeBounds = true;
    
    Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);


    設置inJustDecodeBounds為true后,decodeFile並不分配空間。但可計算出原始圖片的長度和寬度,即opts.width和opts.height。有了這兩個參數,再通過一定的算法,就可以得到一個恰當的inSampleSize。


  • public static Bitmap createImageThumbnail(String filePath){  
  •      Bitmap bitmap = null;  
  •      BitmapFactory.Options opts = new BitmapFactory.Options();  
  •      opts.inJustDecodeBounds = true;  
  •      BitmapFactory.decodeFile(filePath, opts);  
  •   
  •      opts.inSampleSize = computeSampleSize(opts, -1128*128);  
  •      opts.inJustDecodeBounds = false;  
  •   
  •      try {  
  •          bitmap = BitmapFactory.decodeFile(filePath, opts);  
  •      }catch (Exception e) {  
  •         // TODO: handle exception  
  •     }  
  •     return bitmap;  
  • }  
  •   
  • public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {  
  •     int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);  
  •     int roundedSize;  
  •     if (initialSize <= 8) {  
  •         roundedSize = 1;  
  •         while (roundedSize < initialSize) {  
  •             roundedSize <<= 1;  
  •         }  
  •     } else {  
  •         roundedSize = (initialSize + 7) / 8 * 8;  
  •     }  
  •     return roundedSize;  
  • }  
  •   
  • private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {  
  •     double w = options.outWidth;  
  •     double h = options.outHeight;  
  •     int lowerBound = (maxNumOfPixels == -1) ?

     1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  

  •     int upperBound = (minSideLength == -1) ?

     128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));  

  •     if (upperBound < lowerBound) {  
  •         // return the larger one when there is no overlapping zone.  
  •         return lowerBound;  
  •     }  
  •     if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
  •         return 1;  
  •     } else if (minSideLength == -1) {  
  •         return lowerBound;  
  •     } else {  
  •         return upperBound;  
  •     }  
  • }  

  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM