Android中的Crop-to-fit图像

时间:2011-03-08 00:16:09

标签: android image-manipulation

我已经尝试了一段时间,我想从Bitmap创建一个壁纸。假设所需的壁纸尺寸为320x480,源图像尺寸为2048x2048。

我不确定裁剪到合适是否是正确的术语,但我想要实现的是获得与所需壁纸尺寸(320x480)具有相同比例的大部分图片。

所以在这种情况下,我希望从源Bitmap获得2048x1365或(确切地说是1365.333 ......),然后将其缩小到320x480。

我尝试的技术是:

1)首先将位图裁剪为2048x1365

bm = Bitmap.createBitmap(bm, xOffset, yOffset, 2048, 1365);

2)将其缩小至320x480

bm = Bitmap.createScaledBitmap(bm, 320, 480, false);

产生了OutOfMemory错误。

有没有办法实现这个目标?

此致

dezull

3 个答案:

答案 0 :(得分:15)

感谢开源,我在第230行找到了Android Gallery源代码here的答案:-D

croppedImage = Bitmap.createBitmap(mOutputX, mOutputY, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(croppedImage);

Rect srcRect = mCrop.getCropRect();
Rect dstRect = new Rect(0, 0, mOutputX, mOutputY);

int dx = (srcRect.width() - dstRect.width()) / 2;
int dy = (srcRect.height() - dstRect.height()) / 2;

// If the srcRect is too big, use the center part of it.
srcRect.inset(Math.max(0, dx), Math.max(0, dy));

// If the dstRect is too big, use the center part of it.
dstRect.inset(Math.max(0, -dx), Math.max(0, -dy));

// Draw the cropped bitmap in the center
canvas.drawBitmap(mBitmap, srcRect, dstRect, null);

答案 1 :(得分:10)

我知道这是一个非常迟到的回复,但这样的事情可能是:

public static Bitmap scaleCropToFit(Bitmap original, int targetWidth, int targetHeight){
    //Need to scale the image, keeping the aspect ration first
    int width = original.getWidth();
    int height = original.getHeight();

    float widthScale = (float) targetWidth / (float) width;
    float heightScale = (float) targetHeight / (float) height;
    float scaledWidth;
    float scaledHeight;

    int startY = 0;
    int startX = 0;

    if (widthScale > heightScale) {
        scaledWidth = targetWidth;
        scaledHeight = height * widthScale;
        //crop height by...
        startY = (int) ((scaledHeight - targetHeight) / 2);
    } else {
        scaledHeight = targetHeight;
        scaledWidth = width * heightScale;
        //crop width by..
        startX = (int) ((scaledWidth - targetWidth) / 2);
    }

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, (int) scaledWidth, (int) scaledHeight, true);

    Bitmap resizedBitmap = Bitmap.createBitmap(scaledBitmap, startX, startY, targetWidth, targetHeight);
    return resizedBitmap;
}

答案 2 :(得分:0)

这里有一个答案可以帮助你完成大部分工作: How to crop an image in android?