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

EGH*_*HDK 17 java android bitmap

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

我的代码:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false);
Run Code Online (Sandbox Code Playgroud)

我希望图像的最大值为960.我该怎么做?设置宽度null不编译.它可能很简单,但我无法绕过它.谢谢

Geo*_*its 55

如果你已经在内存中的原始位图,你并不需要做的全过程inJustDecodeBounds,inSampleSize等你只需要弄清楚用什么比例,并相应扩大.

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);
Run Code Online (Sandbox Code Playgroud)

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


Tob*_*iel 20

你的图像是方形的,因为你正在设置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;
}
Run Code Online (Sandbox Code Playgroud)

  • 问题是你可以通过这个代码来防止这种情况导致OOM出于多种原因.这是关于位图的android文档:http://developer.android.com/training/displaying-bitmaps/index.html (3认同)