Resizing a bitmap to a fixed value but without changing the aspect ratio

后端 未结 5 1520
清歌不尽
清歌不尽 2021-02-02 16:41

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 conte

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 17:29

    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;

    public static Bitmap resizeBitmapImageForFitSquare(Bitmap image, int maxResolution) {
    
        if (maxResolution <= 0)
            return image;
    
        int width = image.getWidth();
        int height = image.getHeight();
        float ratio = (width >= height) ? (float)maxResolution/width :(float)maxResolution/height;
    
        int finalWidth = (int) ((float)width * ratio);
        int finalHeight = (int) ((float)height * ratio);
    
        image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
    
        if (image.getWidth() == image.getHeight())
            return image;
        else {
            //fit height and width
            int left = 0;
            int top = 0;
    
            if(image.getWidth() != maxResolution)
                left = (maxResolution - image.getWidth()) / 2;
    
            if(image.getHeight() != maxResolution)
                top = (maxResolution - image.getHeight()) / 2;
    
            Bitmap bitmap = Bitmap.createBitmap(maxResolution, maxResolution, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(image, left, top, null);
            canvas.save();
            canvas.restore();
    
            return  bitmap;
        }
    }
    

提交回复
热议问题