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

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

    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) {
            // landscape
            float ratio = (float) width / maxWidth;
            width = maxWidth;
            height = (int)(height / ratio);
        } else if (height > width) {
            // portrait
            float 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;
    }
    

提交回复
热议问题