0%

一行代码实现高斯模糊

前言:有一个音乐播放器的项目,背景需要根据歌曲的封面进行模糊展示,搜罗了很久,找到一个不错的解决方案,不需要我们进行NDK的开发,android帮我们在framework实现好了借鉴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 模糊图片
* @param bitmap 原图片
* @param radius 模糊度 0~25
* @param context
* @return 模糊后的图片
*/
public static Bitmap blurBitmap(Bitmap bitmap, float radius, Context context) {
//Create renderscript
RenderScript rs = RenderScript.create(context);

//Create allocation from Bitmap
Allocation allocation = Allocation.createFromBitmap(rs, bitmap);

Type t = allocation.getType();

//Create allocation with the same type
Allocation blurredAllocation = Allocation.createTyped(rs, t);

//Create script
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//Set blur radius (maximum 25.0)
blurScript.setRadius(radius);
//Set input for script
blurScript.setInput(allocation);
//Call script for output allocation
blurScript.forEach(blurredAllocation);

//Copy script result into bitmap
blurredAllocation.copyTo(bitmap);

//Destroy everything to free memory
allocation.destroy();
blurredAllocation.destroy();
blurScript.destroy();
t.destroy();
rs.destroy();
return bitmap;
}

感谢android,感谢开源