Fast Bitmap Blur For Android SDK

后端 未结 19 1473
情书的邮戳
情书的邮戳 2020-11-22 08:53

Currently in an Android application that I\'m developing I\'m looping through the pixels of an image to blur it. This takes about 30 seconds on a 640x480 image.

W

相关标签:
19条回答
  • 2020-11-22 09:43

    We tried to implement RenderScript blur like mentioned above in different answers. We were limited to use the v8 RenderScript version and that caused us a lot of trouble.

    • Samsung S3 crashed randomly whenever we tried to use the renderscript
    • Other devices (across different APIs) randomly showed different color issues

    I want to share our dirty Java-only version which is slow and should be done on a separate thread and, if possible, before usage and therefore persisted.

    private final Paint mPaint = new Paint();
    
    public Bitmap blur(final String pathToBitmap) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        final Bitmap normalOne = BitmapFactory.decodeFile(pathToBitmap, options);
        final Bitmap resultBitmap = Bitmap.createBitmap(options.outWidth, options.outHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        mPaint.setAlpha(180);
        canvas.drawBitmap(normalOne, 0, 0, mPaint);
        int blurRadius = 12;
        for (int row = -blurRadius; row < blurRadius; row += 2) {
            for (int col = -blurRadius; col < blurRadius; col += 2) {
                if (col * col + row * row <= blurRadius * blurRadius) {
                    mPaint.setAlpha((blurRadius * blurRadius) / ((col * col + row * row) + 1) * 2);
                    canvas.drawBitmap(normalOne, row, col, mPaint);
                }
            }
        }
        normalOne.recycle();
        return resultBitmap;
    }
    

    This solution is far from perfect but creates a reasonable blur effect based on the fact, that it draws highly transparent version of the same image on top of a barely transparent "sharp" version. The alpha depends on the distance to the origin.

    You can adjust some "magic numbers" to your needs. I just wanted to share that "solution" for everybody who has issues with the v8 support version of RenderScript.

    0 讨论(0)
提交回复
热议问题