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

后端 未结 5 1521
清歌不尽
清歌不尽 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:28

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

     private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
        if (maxHeight > 0 && maxWidth > 0) {
            int width = image.getWidth();
            int height = image.getHeight();
            float ratioBitmap = (float) width / (float) height;
            float ratioMax = (float) maxWidth / (float) maxHeight;
    
            int finalWidth = maxWidth;
            int finalHeight = 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;
        }
    }
    

提交回复
热议问题