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

时间:2021-05-20

在市面上很多的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创建一个空的bitmapBitmap 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实现图片的高斯模糊,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章