高斯模糊效果实现方案及性能对比

如今愈来愈多的app在背景图中使用高斯模糊效果,如yahoo天气,效果作得很炫。 这里就用一个demo来谈谈它的不一样实现方式及各自的优缺点。html


1. RenderScript

谈到高斯模糊,第一个想到的就是RenderScript。RenderScript是由Android3.0引入,用来在Android上编写高性能代码的一种语言(使用C99标准)。 引用官方文档的描述:java

RenderScript runtime will parallelize work across all processors available on a device, such as multi-core CPUs, GPUs, or DSPs, allowing you to focus on expressing algorithms rather than scheduling work or load balancing.android

为了在Android中使用RenderScript,咱们须要(直接贴官方文档,比直译更通俗易懂):git

  • High-performance compute kernels are written in a C99-derived language.程序员

  • A Java API is used for managing the lifetime of RenderScript resources and controlling kernel execution.github

学习文档:http://developer.android.com/guide/topics/renderscript/compute.htmlexpress

上面两点总结成一句话为:咱们须要一组compute kernels(.rs文件中编写),及一组用于控制renderScript相关的java api(.rs文件自动生成为java类)。 因为compute kernels的编写须要必定的学习成本,从JELLY_BEAN_MR1开始,Androied内置了一些compute kernels用于经常使用的操做,其中就包括了Gaussian blurcanvas

下面,经过实操来说解一下RenderScript来实现高斯模糊,最终实现效果(讲文字背景进行模糊处理):api

布局:app

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3. android:layout_width="match_parent"  

  4. android:layout_height="match_parent" >  

  5.   

  6.     <ImageView   

  7.         android:id="@+id/picture"   

  8.         android:layout_width="match_parent"   

  9.         android:layout_height="match_parent"   

  10.         android:src="@drawable/splash"   

  11.         android:scaleType="centerCrop" />  

  12.   

  13.     <TextView   

  14.         android:id="@+id/text"  

  15.         android:gravity="center_horizontal"   

  16.         android:layout_width="match_parent"  

  17.         android:layout_height="wrap_content"  

  18.         android:text="Gaussian Blur"  

  19.         android:textColor="@android :color/black"  

  20.         android:layout_gravity="center_vertical"  

  21.         android:textStyle="bold"  

  22.         android:textSize="48sp" />  

  23.   

  24.     <LinearLayout   

  25.         android:id="@+id/controls"   

  26.         android:layout_width="match_parent"   

  27.         android:layout_height="wrap_content"   

  28.         android:background="#7f000000"   

  29.         android:orientation="vertical"  

  30.         android:layout_gravity="bottom" />  

  31. </FrameLayout>  

核心代码:

[java] view plaincopy在CODE上查看代码片派生到个人代码片

  1. private void applyBlur() {  

  2.     image.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {  

  3.   

  4.         @Override  

  5.         public boolean onPreDraw() {  

  6.             image.getViewTreeObserver().removeOnPreDrawListener(this);  

  7.             image.buildDrawingCache();  

  8.             Bitmap bmp = image.getDrawingCache();  

  9.             blur(bmp, text, true);  

  10.             return true;  

  11.         }  

  12.     });  

  13. }  

  14.   

  15. @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)  

  16. private void blur(Bitmap bkg, View view) {  

  17.     long startMs = System.currentTimeMillis();  

  18.     float radius = 20;  

  19.   

  20.     Bitmap overlay = Bitmap.createBitmap((int)(view.getMeasuredWidth()), (int)(view.getMeasuredHeight()), Bitmap.Config.ARGB_8888);  

  21.     Canvas canvas = new Canvas(overlay);  

  22.     canvas.translate(-view.getLeft(), -view.getTop());  

  23.     canvas.drawBitmap(bkg, 00null);  

  24.   

  25.     RenderScript rs = RenderScript.create(SecondActivity.this);  

  26.   

  27.     Allocation overlayAlloc = Allocation.createFromBitmap(rs, overlay);  

  28.     ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, overlayAlloc.getElement());  

  29.     blur.setInput(overlayAlloc);  

  30.     blur.setRadius(radius);  

  31.     blur.forEach(overlayAlloc);  

  32.     overlayAlloc.copyTo(overlay);  

  33.     view.setBackground(new BitmapDrawable(getResources(), overlay));  

  34.     rs.destroy();  

  35.   

  36.     statusText.setText("cost " + (System.currentTimeMillis() - startMs) + "ms");  

  37. }  

当ImageView开始加载背景图时,取出它的drawableCache,进行blur处理,Gaussian blur的主要逻辑在blur函数中。对于在Java中使用RenderScript,文档中也有详细描述,对应到咱们的代码,步骤为:

  • 初始化一个RenderScript Context.

  • 至少建立一个Allocation对象用于存储须要处理的数据.

  • 建立compute kernel的实例,本例中是内置的ScriptIntrinsicBlur对象.

  • 设置ScriptIntrinsicBlur实例的相关属性,包括Allocation, radius等.

  • 开始blur操做,对应(forEach).

  • 将blur后的结果拷贝回bitmap中。

此时,咱们便获得了一个通过高斯模糊的bitmap。 

从上图能够看到,模糊处理花费了38ms(测试机为小米2s),因为Android假设每一帧的处理时间不能超过16ms(屏幕刷新频率60fps),所以,若在主线程里执行RenderScript操做,可能会形成卡顿现象。最好的方式是将其放入AsyncTask中执行。

此外,RenderScript在3.0引入,而一些内置的compute kernelJELLY_BEAN_MR1中引入,为了在低版本手机中使用这些特性,咱们不得不引入renderscript_v8兼容包,对于手Q安装包增量的硬性指标,貌似只能放弃JELLY_BEAN_MR1如下的用户?

有点不甘心,想一想别的解决方案吧。

2. FastBlur

因为高斯模糊归根结底是像素点的操做,也许在java层能够直接操做像素点来进行模糊化处理。google一下,果不其然,一个名为stackblur的开源项目提供了名为fastBlur的方法在java层直接进行高斯模糊处理。

项目地址请猛戳: stackblur

ok,如今来改造咱们的程序.

[java] view plaincopy在CODE上查看代码片派生到个人代码片

  1. private void blur(Bitmap bkg, View view) {  

  2.     long startMs = System.currentTimeMillis();  

  3.     float radius = 20;  

  4.   

  5.     Bitmap overlay = Bitmap.createBitmap((int)(view.getMeasuredWidth()), (int)(view.getMeasuredHeight()), Bitmap.Config.ARGB_8888);  

  6.     Canvas canvas = new Canvas(overlay);  

  7.     canvas.translate(-view.getLeft(), -view.getTop());  

  8.     canvas.drawBitmap(bkg, 00null);  

  9.     overlay = FastBlur.doBlur(overlay, (int)radius, true);  

  10.     view.setBackground(new BitmapDrawable(getResources(), overlay));  

  11.     statusText.setText("cost " + (System.currentTimeMillis() - startMs) + "ms");  

  12. }    

这里,仅仅是把RenderScript相关的操做换成了FastBlur提供的api。效果图以下: 

效果还不错,与RenderScript的实现差很少,但花费的时间却整整多了2倍多,这彻底是没法接受的。好吧,只能继续探究。

3. AdvancedFastBlur

stackOverflow对于程序员来讲永远是最大的宝藏。http://stackoverflow.com/questions/2067955/fast-bitmap-blur-for-android-sdk这篇提问帖终于提供了新的解决思路:

This is a shot in the dark, but you might try shrinking the image and then enlarging it again. This can be done with Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter). Make sure and set the filter parameter to true. It'll run in native code so it might be faster.

它所表述的原理为先经过缩小图片,使其丢失一些像素点,接着进行模糊化处理,而后再放大到原来尺寸。因为图片缩小后再进行模糊处理,须要处理的像素点和半径都变小,从而使得模糊处理速度加快。 了解原理,继续改善:

[java] view plaincopy在CODE上查看代码片派生到个人代码片

  1. private void blur(Bitmap bkg, View view) {  

  2.     long startMs = System.currentTimeMillis();  

  3.     float radius = 2;  

  4.     float scaleFactor = 8;  

  5.   

  6.     Bitmap overlay = Bitmap.createBitmap((int)(view.getMeasuredWidth()/scaleFactor), (int)(view.getMeasuredHeight()/scaleFactor), Bitmap.Config.ARGB_8888);  

  7.     Canvas canvas = new Canvas(overlay);  

  8.     canvas.translate(-view.getLeft()/scaleFactor, -view.getTop()/scaleFactor);  

  9.     canvas.scale(1 / scaleFactor, 1 / scaleFactor);  

  10.     Paint paint = new Paint();  

  11.     paint.setFlags(Paint.FILTER_BITMAP_FLAG);  

  12.     canvas.drawBitmap(bkg, 00, paint);  

  13.     overlay = FastBlur.doBlur(overlay, (int)radius, true);  

  14.     view.setBackground(new BitmapDrawable(getResources(), overlay));  

  15.     statusText.setText("cost " + (System.currentTimeMillis() - startMs) + "ms");  

  16. }   

最新的代码所建立的bitmap为原图的1/8大小,接着,一样使用fastBlur来进行模糊化处理,最后再为textview设置背景,此时,背景图会自动放大到初始大小。注意,因为这里进行了缩放,radius的取值也要比以前小得多(这里将原始取值除以8获得近似值2)。下面是效果图:

惊呆了有木有!!效果同样,处理速度却快得惊人。它相对于renderScript方案来讲,节省了拷贝bitmap到Allocation中,处理完后再拷贝回来的时间开销。

4. Warning

因为FastBlur是将整个bitmap拷贝到一个临时的buffer中进行像素点操做,所以,它不适合处理一些过大的背景图(很容致使OOM有木有~)。对于开发者来讲,RenderScript方案和FastBlur方案的选择,须要你根据具体业务来衡量!

相关文章
相关标签/搜索