Rotate an image file without changing file size

2019-08-07 08:53发布

I want to rotate an image file (photo) without changing file size :

  • I create a bitmap with Bitmap.decodeFile
  • I apply the rotation :

    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    
  • I save bitmap into a file with :

    bitmap.compress(CompressFormat.JPEG, 100, stream);
    

but the size of my original file has doubled !!

2条回答
该账号已被封号
2楼-- · 2019-08-07 09:22

The image you load is encoded in a certain format (e.g. JPEG) and with a certain compression quality (where better quality equals larger file size). When you save it after rotating, you are specifying a potentially completely different format and compression quality, hence the size difference.

I don't think there is any way you can guarantee the same size unless both the input and output files are uncompressed bitmaps, but you can probably at least try to figure out what format and quality was used for the original image and use those settings when you save the file again using bitmap.compress . That should give you a file size in the same ballpark at least.

查看更多
看我几分像从前
3楼-- · 2019-08-07 09:36

Apart from the comppression format try to create the Bitmap with the same config as the src image. I would suggest a RGB_565: http://developer.android.com/reference/android/graphics/Bitmap.Config.html

This would result in a better values as the default one.

mCanvas = new Canvas();
mBitmap = Bitmap.createBitmap(this.width, this.height,
    Bitmap.Config.RGB_565);
mCanvas.setBitmap(mBitmap);

Now if you render any think to mCanvas it will be saved in the bitmap:

mCanvas.save();
mCanvas.translate or roate
mCanvas.drawBitmap(<your real bitmap here>)
mCanvas.restore();

Now mBitmap should have all you need (and the size).

查看更多
登录 后发表回答