Reduce size of Bitmap to some specified pixel in Android

前端 未结 4 2271
北荒
北荒 2020-12-03 02:30

I would like to reduce My Bitmap image size to maximum of 640px. For example I have Bitmap image of size 1200 x 1200 px .. How can I reduce it to 640px.

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 03:29

    If you pass bitmap width and height then use:

    public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth, int bitmapHeight) {
        return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight, true);
    }
    

    If you want to keep the bitmap ratio the same, but reduce it to a maximum side length, use:

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

提交回复
热议问题