简体   繁体   中英

How to use Renderscript to blur a large image into a smaller one?

Background

Suppose I have a rather large bitmap, and I want to blur it into a smaller bitmap.

I actually ask this because I got weird crashes within Renderscript itself on some rare devices, so maybe it's something with the input (which in fact I already make sure is quite small):

java.lang.OutOfMemoryError: Failed to allocate a 1920169996 byte allocation with 16777216 free bytes and 67MB until OOM
   at android.renderscript.RenderScript$MessageThread.run(RenderScript.java:1111)

It's weird, because there is no way the input bitmap is so large (almost 2GB?!).

The problem

The code below tries to do it, but for some reason, the output bitmap takes only the top-left area of the large bitmap into itself:

        outputBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outputBitmap);
        canvas.drawBitmap(srcBitmap, 0, 0, null);
        Allocation overlayAlloc = Allocation.createFromBitmap(rs, outputBitmap, MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE);
        ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        blur.setInput(overlayAlloc);
        blur.setRadius(radius);
        blur.forEach(overlayAlloc);
        overlayAlloc.copyTo(outputBitmap);
        rs.destroy();
        return outputBitmap;

The question

How could this be? What should be done to fix it? Obviously, I could create a new bitmap as the input, and make it the same size as the small one, but this creates yet another bitmap that takes memory, and I'd like to avoid it.

Before trying to save memory without creating small bitmaps try to check this: http://trickyandroid.com/advanced-blurring-techniques/

You can save time if you downscale you image, blur it and then upscale - there is no big difference between tricky blur and fair blur but it saves time.

PS. also you can check renderscript sample from this topic. PSS. also you can check this thread about blur: Fast Bitmap Blur For Android SDK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM