Skip to content Skip to sidebar Skip to footer

Resizing A Bitmap To A Fixed Value But Without Changing The Aspect Ratio

I'm looking for a solution for the following problem: how to change the size of a Bitmapto a fixed size (for example 512x128). The aspect ratio of the bitmap content must be preser

Solution 1:

Try this, calculate the ratio and then rescale.

private Bitmap scaleBitmap(Bitmap bm){
    int width = bm.getWidth();
    int height = bm.getHeight();

    Log.v("Pictures", "Width and height are " + width + "--" + height);

    if (width > height) {
        // landscapefloat ratio = (float) width / maxWidth;
        width = maxWidth;
        height = (int)(height / ratio);
    } elseif (height > width) {
        // portraitfloat ratio = (float) height / maxHeight;
        height = maxHeight;
        width = (int)(width / ratio);
    } else {
        // square
        height = maxHeight;
        width = maxWidth;
    }

    Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);

    bm = Bitmap.createScaledBitmap(bm, width, height, true);
    return bm;
}

Solution 2:

The answer by Coen Damen doesn't always respect Max Height and Max Width. Here's an answer that does:

privatestatic Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
    if (maxHeight > 0 && maxWidth > 0) {
        intwidth= image.getWidth();
        intheight= image.getHeight();
        floatratioBitmap= (float) width / (float) height;
        floatratioMax= (float) maxWidth / (float) maxHeight;

        intfinalWidth= maxWidth;
        intfinalHeight= maxHeight;
        if (ratioMax > 1) {
            finalWidth = (int) ((float)maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float)maxWidth / ratioBitmap);
        }
        image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
        return image;
    } else {
        return image;
    }
}

Solution 3:

I have stumbled upon the same problem a number of times in my projects and each time due to lack of time (and laziness) I would be satisfied with a less than optimum solution. But recently I found some time to crack down this particular issue. Here is my solution and I hope it helps someone down the line.

Bitmap scaleDownLargeImageWithAspectRatio(Bitmap image)
            {
                int imageVerticalAspectRatio,imageHorizontalAspectRatio;
                float bestFitScalingFactor=0;
                float percesionValue=(float) 0.2;
    
                //getAspect Ratio of Imageint imageHeight=(int) (Math.ceil((double) image.getHeight()/100)*100);
                int imageWidth=(int) (Math.ceil((double) image.getWidth()/100)*100);
                int GCD=BigInteger.valueOf(imageHeight).gcd(BigInteger.valueOf(imageWidth)).intValue();
                imageVerticalAspectRatio=imageHeight/GCD;
                imageHorizontalAspectRatio=imageWidth/GCD;
                Log.i("scaleDownLargeImageWIthAspectRatio","Image Dimensions(W:H): "+imageWidth+":"+imageHeight);
                Log.i("scaleDownLargeImageWIthAspectRatio","Image AspectRatio(W:H): "+imageHorizontalAspectRatio+":"+imageVerticalAspectRatio);
    
                //getContainer DimensionsintdisplayWidth= getWindowManager().getDefaultDisplay().getWidth();
                intdisplayHeight= getWindowManager().getDefaultDisplay().getHeight();
               //I wanted to show the image to fit the entire device, as a best case. So my ccontainer dimensions were displayWidth & displayHeight. For your case, you will need to fetch container dimensions at run time or you can pass static values to these two parameters intleftMargin=0;
                intrightMargin=0;
                inttopMargin=0;
                intbottomMargin=0;
                intcontainerWidth= displayWidth - (leftMargin + rightMargin);
                intcontainerHeight= displayHeight - (topMargin + bottomMargin);
                Log.i("scaleDownLargeImageWIthAspectRatio","Container dimensions(W:H): "+containerWidth+":"+containerHeight);
    
                //iterate to get bestFitScaleFactor per constraintswhile((imageHorizontalAspectRatio*bestFitScalingFactor <= containerWidth) && 
                        (imageVerticalAspectRatio*bestFitScalingFactor<= containerHeight))
                {
                    bestFitScalingFactor+=percesionValue;
                }
    
                //return bestFit bitmapint bestFitHeight=(int) (imageVerticalAspectRatio*bestFitScalingFactor);
                int bestFitWidth=(int) (imageHorizontalAspectRatio*bestFitScalingFactor);
                Log.i("scaleDownLargeImageWIthAspectRatio","bestFitScalingFactor: "+bestFitScalingFactor);
                Log.i("scaleDownLargeImageWIthAspectRatio","bestFitOutPutDimesions(W:H): "+bestFitWidth+":"+bestFitHeight);
                image=Bitmap.createScaledBitmap(image, bestFitWidth,bestFitHeight, true);
    
                //Position the bitmap centre of the containerint leftPadding=(containerWidth-image.getWidth())/2;
                int topPadding=(containerHeight-image.getHeight())/2;
                Bitmap backDrop=Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.RGB_565);
                Canvascan=newCanvas(backDrop);
                can.drawBitmap(image, leftPadding, topPadding, null);
    
                return backDrop;
            }

Solution 4:

Solution 5:

I think @Coen's answer is not right solution for this question. I also needed a method like this but I wanted to square image.

Here is my solution for square image;

publicstatic Bitmap resizeBitmapImageForFitSquare(Bitmap image, int maxResolution) {

    if (maxResolution <= 0)
        return image;

    intwidth= image.getWidth();
    intheight= image.getHeight();
    floatratio= (width >= height) ? (float)maxResolution/width :(float)maxResolution/height;

    intfinalWidth= (int) ((float)width * ratio);
    intfinalHeight= (int) ((float)height * ratio);

    image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);

    if (image.getWidth() == image.getHeight())
        return image;
    else {
        //fit height and widthintleft=0;
        inttop=0;

        if(image.getWidth() != maxResolution)
            left = (maxResolution - image.getWidth()) / 2;

        if(image.getHeight() != maxResolution)
            top = (maxResolution - image.getHeight()) / 2;

        Bitmapbitmap= Bitmap.createBitmap(maxResolution, maxResolution, Bitmap.Config.ARGB_8888);
        Canvascanvas=newCanvas(bitmap);
        canvas.drawBitmap(image, left, top, null);
        canvas.save();
        canvas.restore();

        return  bitmap;
    }
}

Post a Comment for "Resizing A Bitmap To A Fixed Value But Without Changing The Aspect Ratio"