【问题标题】:Use BitmapFactory to load cropped image from stream/file使用 BitmapFactory 从流/文件中加载裁剪的图像
【发布时间】:2015-03-07 01:14:17
【问题描述】:

有没有一种简单的方法可以使用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;
}

【问题讨论】:

    标签: android image crop bitmapfactory


    【解决方案1】:

    你应该使用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

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多