在 Android 中使用 createScaledBitmap 创建缩放位图

2022-09-01 19:39:02

我想创建一个缩放的位图,但我似乎得到了一个不成比例的图像。它看起来像一个正方形,而我想成为矩形。

我的代码:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false);

我希望图像的最大值为 960。我该怎么做?将宽度设置为 不编译。这可能很简单,但我不能把我的头缠绕在它上面。谢谢null


答案 1

如果内存中已有原始位图,则无需执行 、 等的整个过程。您只需要弄清楚要使用的比例并相应地进行扩展即可。inJustDecodeBoundsinSampleSize

final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = myBitmap.getWidth();
int inHeight = myBitmap.getHeight();
if(inWidth > inHeight){
    outWidth = maxSize;
    outHeight = (inHeight * maxSize) / inWidth; 
} else {
    outHeight = maxSize;
    outWidth = (inWidth * maxSize) / inHeight; 
}

Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, outWidth, outHeight, false);

如果此图像的唯一用途是缩放版本,则最好使用Tobiel的答案,以最大程度地减少内存使用。


答案 2

您的图像是正方形的,因为您正在设置 和 。width = 960height = 960

您需要创建一个方法,在其中传递所需图像的大小,如下所示:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

在代码中,这看起来像这样:

public static Bitmap lessResolution (String filePath, int width, int height) {
    int reqHeight = height;
    int reqWidth = width;
    BitmapFactory.Options options = new BitmapFactory.Options();    

    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;        

    return BitmapFactory.decodeFile(filePath, options); 
}

private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
}

推荐