javaandroidbitmapandroid-bitmap

Resize Bitmap to 512x512 Without changing original aspect ratio


I have a created bitmaps. Sizes are not specific. Sometimes 120x60 , 129x800 , 851x784. Its not have a specific value... I want to make these bitmaps resizing to 512x512 always but without changing original images aspect ratio. And without cropping. New image must have canvas 512x512 and original image must be center without any cropping.

I was resizing my bitmaps with this function but it makes images really bad because image fitting X and Y . I don't want image to fit x and y on same time fits one of it and keeps its aspect ratio.

From https://thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/ :

 public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }

What I have;

enter image description here

What I want;

enter image description here


Solution

  • Ok, so you're really close. I can't test this right now, but basically what needs to be changed is

    1) You need to apply the same scale to both X and Y, so you need to pick the smaller one (try the bigger one if that doesn't work).

    matrix.postScale(Math.min(scaleWidth, scaleHeight), Math.min(scaleWidth, scaleHeight));
    

    2) The result will be a bitmap where at least one side is 512px large, the other one will be smaller. So you need to add the padding to fit that side to 512px (equally left and right/top and bottom for centering). In order to do so, you need to create an new bitmap of the desired size:

    Bitmap outputimage = Bitmap.createBitmap(512,512, Bitmap.Config.ARGB_8888);
    

    3) and lastly depending on what side of the resizedBitmap is 512px you need to draw resizedBitmap to the correct position in outputImage

    Canvas can = new Canvas(outputimage);
    can.drawBitmap(resizedBitmap, (512 - resizedBitmap.getWidth()) / 2, (512 - resizedBitmap.getHeight()) / 2, null);
    

    Note here, that 512 - resizedBitmap.getWidth() results in 0 and therefor no padding at the side with correct size.

    4) Now return outputImage