当前位置: 移动技术网 > 移动技术>移动开发>Android > Android实现图片的高斯模糊(两种方式)

Android实现图片的高斯模糊(两种方式)

2019年07月24日  | 移动技术网移动技术  | 我要评论

在市面上很多的app都使用了对图片作模糊化处理后作为背景的效果,来使得整个页面更具有整体感。如下就是网易云音乐的音乐播放页面:

很明显这个页面的背景是由中间的小图片模糊化后而来的。最常用的模糊化处理就是高斯模糊。

高斯模糊的几种实现方式:

(1)renderscript

renderscript是google在android 3.0(api 11)中引入的一个高性能图片处理框架。

使用renderscriprt实现高斯模糊:

首先在在build.gradle的defaultconfig中添加renderscript的使用配置

renderscripttargetapi 24
renderscriptsupportmodeenabled true

renderscripttargetapi :

指定要生成的字节码版本。我们(goole官方)建议您将此值设置为最低api级别能够提供所有的功能,你使用和设置renderscriptsupportmodeenabled为true。此设置的有效值是从11到
最近发布的api级别的任何整数值。

renderscriptsupportmodeenabled:

指定生成的字节码应该回落到一个兼容的版本,如果运行的设备不支持目标版本。

下面就是使用renderscriprt实现高斯模糊的方法:

public static bitmap blurbitmap(context context, bitmap bitmap) {
 //用需要创建高斯模糊bitmap创建一个空的bitmap
bitmap outbitmap = bitmap.createbitmap(bitmap.getwidth(), bitmap.getheight(), bitmap.config.argb_8888);
 // 初始化renderscript,该类提供了renderscript context,创建其他rs类之前必须先创建这个类,其控制renderscript的初始化,资源管理及释放
 renderscript rs = renderscript.create(context);
 // 创建高斯模糊对象
 scriptintrinsicblur blurscript = scriptintrinsicblur.create(rs, element.u8_4(rs));
 // 创建allocations,此类是将数据传递给renderscript内核的主要方 法,并制定一个后备类型存储给定类型
 allocation allin = allocation.createfrombitmap(rs, bitmap);
 allocation allout = allocation.createfrombitmap(rs, outbitmap);
 //设定模糊度(注:radius最大只能设置25.f)
 blurscript.setradius(15.f);
 // perform the renderscript
 blurscript.setinput(allin);
 blurscript.foreach(allout);
 // copy the final bitmap created by the out allocation to the outbitmap
 allout.copyto(outbitmap);
 // recycle the original bitmap
 // bitmap.recycle();
 // after finishing everything, we destroy the renderscript.
 rs.destroy();
 return outbitmap;
 }

(2)glide实现高斯模糊

glide是一个比较强大也是比较常用的一个图片加载库,glide中的transformations用于在图片显示前对图片进行处理。glide-transformations 这个库为glide提供了多种多样的 transformations实
现,其中就包括高斯模糊的实现blurtransformation

compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'jp.wasabeef:glide-transformations:2.0.1' 

 通过这两个库的结合使用,就可以使用其中的blurtransformation实现图片的高斯模糊

glide.with(context).load(r.drawable.defalut_photo).bitmaptransform(new blurtransformation(context, radius)).into(mimageview);

其中radius的取值范围是1-25,radius越大,模糊度越高。

以上所述是小编个大家介绍的android实现图片的高斯模糊,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网