android图片处理之图像模糊

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/kangaroo835127729/article/details/47027069

这篇文章将给大家介绍android图片处理的高效做法,大家有需求的时候可以参考一下。

首先我要说明一下本实例中实现的效果(我还不会制作gif图,如果谁会的话,希望可以教一下我):通过手指对图片的上下滑动,实现图片的逐渐模糊效果。

找网上找了一张效果图如下(侵权请通知删除):



下面我来讲解一下效果制作的思路。

首先是对图像的模糊处理,最常见的模糊处理方式是高斯模糊,高斯模糊指定一个半径radius,对于图片上的每个像素点,以其为中心,有一个radius长的正方形(边界点除外,但是可以使用对称的方式计算),对于这个正方形上的每一个点,和权值(权值是根据正态分布函数计算出来的)相乘以后相加,再求平均,用该平均值代替中心点的值。

高斯模糊效率比较低,处理时间很长,github上有一个快速模糊的算法,接下来我们也会用到。

另外,android其实提供了一个高效的图片处理库RenderScript,使用这个库我们也可以快速的进行图片模糊。

下面来看我写的,一个图片模糊处理的类

public class BitmapBlurHelper {
    //缩放系数
    public final static int SCALE = 8;

    /**
     * 模糊函数
     * @param context
     * @param sentBitmap
     * @param radius
     * @return
     */
    public static Bitmap doBlur(Context context, Bitmap sentBitmap, float radius) {
        if(sentBitmap==null) return null;
        if (radius <= 0 || radius > 25) radius = 25f;//范围在1-25之间
        if (radius<=6&&VERSION.SDK_INT > 16) {//经测试,radius大于6后,fastBlur效率更高,并且RenderScript在api11以上使用
            Bitmap bitmap = Bitmap.createScaledBitmap(sentBitmap, sentBitmap.getWidth()/SCALE,sentBitmap.getHeight()/SCALE,false);//先缩放图片,增加模糊速度
            final RenderScript rs = RenderScript.create(context);
            final Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            final Allocation output = Allocation.createTyped(rs, input.getType());
            final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            script.setRadius(radius);
            script.setInput(input);
            script.forEach(output);
            output.copyTo(bitmap);
            rs.destroy();
            return bitmap;
        }else{//快速模糊
            return fastBlur(sentBitmap,radius);
        }
    }

    /**
     * 快速模糊算法
     * @param sbitmap
     * @param radiusf
     * @return
     * Stack Blur v1.0 from
     * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
     * Java Author: Mario Klingemann <mario at quasimondo.com>
     * http://incubator.quasimondo.com
     * created Feburary 29, 2004
     * Android port : Yahel Bouaziz <yahel at kayenko.com>
     * http://www.kayenko.com
     * ported april 5th, 2012

     * This is a compromise between Gaussian Blur and Box blur
     * It creates much better looking blurs than Box Blur, but is
     * 7x faster than my Gaussian Blur implementation.
     * I called it Stack Blur because this describes best how this
     * filter works internally: it creates a kind of moving stack
     * of colors whilst scanning through the image. Thereby it
     * just has to add one new block of color to the right side
     * of the stack and remove the leftmost color. The remaining
     * colors on the topmost layer of the stack are either added on
     * or reduced by one, depending on if they are on the right or
     * on the left side of the stack.
     * If you are using this algorithm in your code please add
     * the following line:
     *
     * Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
     */
    public static Bitmap fastBlur(Bitmap sbitmap, float radiusf){
        Bitmap bitmap = Bitmap.createScaledBitmap(sbitmap, sbitmap.getWidth()/SCALE,sbitmap.getHeight()/SCALE,false);//先缩放图片,增加模糊速度
        int radius = (int)radiusf;
        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return (bitmap);
    }
}

从上面的代码我们可以看到,我首先对图片进行了比例缩放,这样做的目的是为了加快模糊处理效率。

如果我们不事先对图片进行缩放,无论是调用快速模糊还是RenderScript,都会需要较长的计算时间,对于最大模糊效果,前者需要2000ms以上,后者需要需要500ms以上,这个效率显然是不能接受的。

我们的模糊系数范围是1-25,因为RenderScript的系数要求就是这个范围(原因不得而知,但是超过了就会抛异常)。

对于图片进行缩放以后,我发现了一个神奇的地方,就是快速模糊的效率居然赶上了RenderScript的效率,在radius为6以下,RenderScript较高,在20ms之内,而快速模糊需要200ms以内,但是在6以后,快速模糊只在20ms以内,而RenderScript则超过20ms,并且随着radius的增大,两者的差距也拉大。

所以在代码中,我们根据6为边界,分别使用两者,另外RenderScript还要求在API 11以上才能使用。


OK,由来图片模糊的处理方法,我们现在想实现图片上的动态效果,简单的思路就是监听手指的移动,然后每次都讲图片进行模糊处理。

这种思路面临一个困难,就是GPU绘制的速度超过了模糊算法的速度,也就是说模糊计算需要较长时间,这样会造成程序的卡顿。


我的解决思路是,首先将图片进行一次最大的模糊处理,得到一张最模糊的图片,然后将清晰图片(在下方)和模糊图片(在上方)叠加,在手指移动过程中,修改模糊图片的透明度,从而实现从清晰到透明的过渡效果。

怎么实现图片叠加呢?我使用了LayerDrawable这个类,并且构造了一个BlurDrawable类

/** 
 * 模糊drawable
 */
public class BlurDrawable{
    //上下两层图片
    private Drawable[] array = new Drawable[2];
    //层叠图片
    private LayerDrawable la;

    /**
     * @param context
     * @param res
     * @param bitmap
     */
    public BlurDrawable(Context context,Resources res, Bitmap bitmap) {
        array[0] = new BitmapDrawable(res,bitmap);
        array[1] = new BitmapDrawable(res,BitmapBlurHelper.doBlur(context,bitmap,25));//生产模糊图片
        array[1].setAlpha(0);
        la = new LayerDrawable(array);
        la.setLayerInset(0, 0, 0, 0, 0);//层叠
        la.setLayerInset(1, 0, 0, 0, 0);
    }

    /**
     * 返回层叠以后的图片
     * @return
     */
    public LayerDrawable getBlurDrawable() {
        return la;
    }

    /**
     * 获得模糊系数,本质上是透明度
     * @return
     */
    public int getBlur(){
        return array[1].getAlpha();
    }

    /**
     * 设置模糊系数
     * @param alpha
     */
    public void setBlur(int alpha){
        array[1].setAlpha(alpha);
    }
}


上面的代码很简单,相信大家也看得懂,最后就是为ImageView设置drawable,然后添加一个onClickListener

        mBlurImage = (ImageView)findViewById(R.id.img);
        final Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ssd);
        final BlurDrawable blurDrawable = new BlurDrawable(this, getResources(),bp);
        mBlurImage.setImageDrawable(blurDrawable.getBlurDrawable());

       
        mBlurImage.setOnTouchListener(new View.OnTouchListener() {

            private float mLastY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mLastY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float y = event.getY();
                        float alphaDelt = (y - mLastY) / 50;
                        int alpha = (int) (blurDrawable.getBlur() + alphaDelt);
                        Log.i("time", alpha + "");
                        if (alpha > 255) {
                            alpha = 255;
                        } else if (alpha < 0.0) {
                            alpha = 0;
                        }
                        blurDrawable.setBlur(alpha);
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return true;
            }
        });        

由于透明度的范围是0-255,我们的模糊系数也从0到255

只有在action_move过程最后,不断修改blurDrawable的透明度就可以了,而且透明度改变方法我也提供了


Ok,到此为止,透明效果就实现了,大家看copy一下代码来看一下,个人认为这段代码是图片模糊处理的较好实现例子。

转载请注明出处哦!


展开阅读全文

没有更多推荐了,返回首页