使用 BitmapFactory 从 stream/file 加载裁剪图像

Use BitmapFactory to load cropped image from stream/file

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

基本上我想节省内存并防止内存不足的情况,同时加载完整的位图只是为了计算缩略图。

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

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

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;
}

你应该使用BitmapRegionDecoder

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

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

示例

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