使用BitmapFactory从流/文件加载裁剪的图像

时间:2015-03-07 01:14:18

标签: android image crop bitmapfactory

是否有一种简单的方法可以使用BitmapFactory.decodeFile()BitmapFactory.decodeStream()直接获取中心裁剪的位图,而不是先加载完整的位图,然后应用位图转换,例如Bitmap cropped = Bitmap.createBitmap(...)?我想当编码已知时,应该只能读取创建裁剪所需的位图的相关部分。

基本上我想在加载完整的位图以计算缩略图时节省内存并防止出现内存不足的情况。

如果有人能指出我正确的方向并给我一些关键词,我会非常感激。

为了完整起见,这里是我目前用于裁剪位图的代码,这是我在stackoverflow上找到的一种方法:

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    // TODO: I think we crash here (null pointer exception) when the receiving image is an animated gif
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

    return dest;
}

1 个答案:

答案 0 :(得分:3)

您应该使用BitmapRegionDecoder

BitmapRegionDecoder可用于解码图像中的矩形区域。当原始图像很大并且您只需要部分图像时,BitmapRegionDecoder特别有用。

要创建BitmapRegionDecoder,请调用newInstance(...)。给定一个BitmapRegionDecoder,用户可以重复调用decodeRegion()来获取指定区域的解码位图。

示例

https://github.com/jdamcd/android-crop/blob/master/lib/src/main/java/com/soundcloud/android/crop/CropImageActivity.java