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

时间:2013-07-24 16:09:40

标签: java android bitmap

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

我的代码:

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

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

3 个答案:

答案 0 :(得分:53)

如果您已在内存中使用原始位图,则无需执行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的答案,以最大限度地减少内存使用。

答案 1 :(得分:18)

您的图片是正方形,因为您设置了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;
}

答案 2 :(得分:1)

bmpimg = Bitmap.createScaledBitmap(srcimg, 100, 50, true);