2016-03-28 87 views
1

我只是試圖壓縮位圖,以便獲得較小尺寸的圖像。 像2MB圖像到-100kb,但保持圖像的高寬比。如何將位圖壓縮爲較小尺寸的圖像(保持縱橫比)

我已經嘗試了一些在線代碼,但它只是不能很好地工作,有時我甚至在壓縮後得到更大的圖像大小。 那麼我該如何做到這一點?! 但反正我發現這個代碼在網上:

private Bitmap getBitmap(int path, Canvas canvas) { 

    Resources resource = null; 
    try { 
     final int IMAGE_MAX_SIZE = 1200000; // 1.2MP 
     resource = getResources(); 

     // Decode image size 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeResource(resource, path, options); 

     int scale = 1; 
     while ((options.outWidth * options.outHeight) * (1/Math.pow(scale, 2)) > 
       IMAGE_MAX_SIZE) { 
      scale++; 
     } 
     Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight); 

     Bitmap pic = null; 
     if (scale > 1) { 
      scale--; 
      // scale to max possible inSampleSize that still yields an image 
      // larger than target 
      options = new BitmapFactory.Options(); 
      options.inSampleSize = scale; 
      pic = BitmapFactory.decodeResource(resource, path, options); 

      // resize to desired dimensions 
      int height = canvas.getHeight(); 
      int width = canvas.getWidth(); 
      Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height); 

      double y = Math.sqrt(IMAGE_MAX_SIZE 
        /(((double) width)/height)); 
      double x = (y/height) * width; 

      Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true); 
      pic.recycle(); 
      pic = scaledBitmap; 

      System.gc(); 
     } else { 
      pic = BitmapFactory.decodeResource(resource, path); 
     } 

     Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight()); 
     return pic; 
    } catch (Exception e) { 
     Log.e("TAG", e.getMessage(),e); 
     return null; 
    } 
} 

我有圖片的路徑,但我不知道什麼是帆布(第二個參數)。 還有沒有更好的方法來壓縮位圖? 謝謝

+0

使用'inSampleSize'會更簡單,因爲它已經保持了寬高比。請參閱https://github.com/commonsguy/cw-omnibus/tree/master/Bitmaps/InSampleSize。 – CommonsWare

回答