在Bitmapfactory中解码图像的特定区域?

时间:2013-10-04 23:18:31

标签: java android bitmapfactory bitmapregiondecoder

我使用的GeoTiff/PNG文件太大,无法在我的代码中进行整体处理。

是否有可能在bitmapfactory中解码文件的特定区域(例如由两个x,y坐标给出)? Haven在http://developer.android.com/reference/android/graphics/BitmapFactory.html(Android的开发人员参考资料)中发现了类似的内容。

谢谢!


通过kcoppock的提示,我已经设置了以下解决方案。

虽然我想知道为什么rect需要Rect(left, bottom, right, top)而不是Rect(left, top, right, bottom)来初始化...

示例电话:

Bitmap myBitmap = loadBitmapRegion(context, R.drawable.heightmap,
    0.08f, 0.32f, 0.13f, 0.27f);

功能:

public static Bitmap loadBitmapRegion(
    Context context, int resourceID,
    float regionLeft, float regionTop,
    float regionRight, float regionBottom) {

    // Get input stream for resource
    InputStream is = context.getResources().openRawResource(resourceID);

    // Set options
    BitmapFactory.Options opt = new BitmapFactory.Options();
    //opt.inPreferredConfig = Bitmap.Config.ARGB_8888; //standard

    // Create decoder
    BitmapRegionDecoder decoder = null;
    try {
        decoder = BitmapRegionDecoder.newInstance(is, false);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Get resource dimensions
    int h = decoder.getHeight();
    int w = decoder.getWidth();

    // Set region to decode
    Rect region = new Rect(
            Math.round(regionLeft*w), Math.round(regionBottom*h),
            Math.round(regionRight*w), Math.round(regionTop*h));

    // Return bitmap
    return decoder.decodeRegion(region, opt);

}

2 个答案:

答案 0 :(得分:2)

我不确切地知道“Decode特定区域”是什么意思,但如果通过解码意味着实际“复制”位图的某些区域,你可以做的就是利用画布来获得它如下图所示:

        Bitmap bmpWithArea = Bitmap.createBitmap(widthDesired, heightDesired, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmpWithArea);
        Rect area = new Rect(arealeft, areatop, arearight, areabottom);
        Rect actualSize = new Rect(0, 0, widthDesired, heightDesired);
        canvas.drawBitmap(bitmapWithAreaYouWantToGet, area, actual, paintIfAny);

        //And done, starting from this line "bmpWithArea" has the bmp that you wanted, you can assign it to ImageView and use it as regular bmp...

希望这会有所帮助......

问候!

答案 1 :(得分:2)

你应该研究BitmapRegionDecoder。它似乎准确描述了您正在寻找的用例。