2016-03-28 31 views
1

私はビットマップを圧縮しようとしていますので、サイズの小さいイメージを取得できます。 イメージのアスペクト比を維持しながら-100kbまでの2mbイメージを好む。ビットマップを低サイズのイメージに圧縮する方法(アスペクト比を維持する)

私はいくつかのコードをオンラインで試してみましたが、うまくいきませんでしたが、圧縮後にさらに大きな画像サイズを取得することさえありました。 どうすればいいですか? はなく、とにかく、私はこのコードをオンラインで見つかりました

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; 
    } 
} 

私は画像のパスを持っているが、私はキャンバス(第2パラメータ)であるのか分かりません。 ビットマップを圧縮するより良い方法はありますか? ありがとう

+0

既にinSampleSizeを使用する方がアスペクト比を維持しているのではるかに簡単です。 https://github.com/commonsguy/cw-omnibus/tree/master/Bitmaps/InSampleSizeを参照してください。 – CommonsWare

答えて

関連する問題