2013-06-06 7 views
7

ビットマップのサイズを正確に200kbに​​縮小したい。私は、sdcardから画像を取得し、圧縮し、別のディレクトリに別の名前でsdcardに再度保存します。圧縮はうまく動作します(3 MBの画像が約100 KBに圧縮されます)。私はこのためのコードの次の行を書いた:ビットマップのサイズをAndroidで指定されたサイズに減らす

String imagefile ="/sdcard/DCIM/100ANDRO/DSC_0530.jpg"; 
Bitmap bm = ShrinkBitmap(imagefile, 300, 300); 

//this method compresses the image and saves into a location in sdcard 
    Bitmap ShrinkBitmap(String file, int width, int height){ 

     BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); 
      bmpFactoryOptions.inJustDecodeBounds = true; 
      Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); 

      int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height); 
      int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width); 

      if (heightRatio > 1 || widthRatio > 1) 
      { 
      if (heightRatio > widthRatio) 
      { 
       bmpFactoryOptions.inSampleSize = heightRatio; 
      } else { 
       bmpFactoryOptions.inSampleSize = widthRatio; 
      } 
      } 

      bmpFactoryOptions.inJustDecodeBounds = false; 
      bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); 

      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
      byte[] imageInByte = stream.toByteArray(); 
      //this gives the size of the compressed image in kb 
      long lengthbmp = imageInByte.length/1024; 

      try { 
       bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/compressed_new.jpg")); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


     return bitmap; 
     } 
+0

変更そのイメージの幅と高さ.. – Riser

+0

イメージを200x200にすることを意味しますか? – TharakaNirmana

+0

ええ、200kbを望みます。結果が得られるまで試してください。 – Riser

答えて

16

私は私のために完璧に動作答えを見つけました:メソッドを呼び出す

/** 
    * reduces the size of the image 
    * @param image 
    * @param maxSize 
    * @return 
    */ 
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) { 
     int width = image.getWidth(); 
     int height = image.getHeight(); 

     float bitmapRatio = (float)width/(float) height; 
     if (bitmapRatio > 1) { 
      width = maxSize; 
      height = (int) (width/bitmapRatio); 
     } else { 
      height = maxSize; 
      width = (int) (height * bitmapRatio); 
     } 
     return Bitmap.createScaledBitmap(image, width, height, true); 
    } 

Bitmap converetdImage = getResizedBitmap(photo, 500); 
  • 写真はあなたですビットマップ
+0

この関数は、ビットマップサイズが大きい場合はビットマップサイズを小さくしますが、それより小さいビットマップの場合は小さくします。仕様どおりに拡大されますか? – NarendraJi

+0

なぜ黒のビットマップになるのですか? – Sermilion

+1

@TharakaNirmana maxSizeとは何ですか?あなたのメソッドの呼び出しでは、500、500 kbまたは500 mbですか? – TheQ

関連する問題