轉(zhuǎn)自 湫水長(zhǎng)天 的博客
湫水長(zhǎng)天 的博客地址:
http://blog.csdn.net/wl9739
高斯模糊是用的是 Android 的 **RenderScript **,使用 **RenderScript 的渲染效率和使用C/C++ **不相上下,但是使用 **RenderScript **卻比使用 **JNI **簡(jiǎn)單地多!
**RenderScript **官方文檔:
https://developer.android.com/guide/topics/renderscript/compute.html
工具類:
public class BlurBitmap {
/**
* 圖片縮放比例
*/
private static final float BITMAP_SCALE = 0.4f;
/**
* 最大模糊度(0.0到25.0之間)
*/
private static final float BLUR_RADIUS = 5f;
/**
* 模糊方法
*
* @param context
* @param image
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static Bitmap blur(Context context, Bitmap image) {
//計(jì)算圖片縮小后的長(zhǎng)寬
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
//將縮小后的圖片作為預(yù)渲染的圖片
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
//創(chuàng)建一張渲染后的輸出圖片
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
//創(chuàng)建RenderScript內(nèi)核對(duì)象
RenderScript rs = RenderScript.create(context);
//創(chuàng)建一個(gè)模糊效果的RenderScript的工具對(duì)象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并沒(méi)有使用VM來(lái)分配內(nèi)存,所以需要使用Allocation類來(lái)創(chuàng)建和分配內(nèi)存空間。
// 創(chuàng)建Allocation對(duì)象的時(shí)候其實(shí)內(nèi)存是空的,需要使用copyTo()將數(shù)據(jù)填充進(jìn)去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
//設(shè)置渲染的模糊程度
blurScript.setRadius(BLUR_RADIUS);
//設(shè)置blurScript對(duì)象的輸入內(nèi)存
blurScript.setInput(tmpIn);
//將輸出數(shù)據(jù)保存到輸出內(nèi)存中
blurScript.forEach(tmpOut);
//將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
其實(shí) RenderScript 還有其他好多方法的,有興趣可以看看。

Paste_Image.png
使用方法:
public class RenderScriptActivity extends AppCompatActivity {
ImageView image;
//原始圖片
private Bitmap mTempBitmap;
//處理后的圖片
private Bitmap mFinalBitmap;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_render_script);
image = (ImageView) findViewById(R.id.image);
//得到原始圖片
mTempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aaa);
//得到處理后的圖片
mFinalBitmap = BlurBitmap.blur(this, mTempBitmap);
//把處理后的圖片顯示出來(lái)
image.setImageBitmap(mFinalBitmap);
}
}
最后別忘了在 build.gradle 中添加:

Paste_Image.png