1. 程式人生 > >android 實現高斯模糊

android 實現高斯模糊

方法一
(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級別的任何整數值。

1.首先在app目錄下build.gradle檔案中新增如下程式碼:

defaultConfig {
        applicationId "io.github.marktony.gaussianblur"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
    }

2.下面就是使用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; }

3.然後就可以直接實現不同程度的模糊了。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
imageView.setImageBitmap(blur.gaussianBlur(radius, bitmap));

方法二:
(2)Glide實現高斯模糊

Glide是一個比較強大也是比較常用的一個圖片載入庫,Glide中的Transformations用於在圖片顯示前對圖片進行處理。glide-transformations 這個庫為Glide提供了多種多樣的Transformations實現,其中就包括高斯模糊的實現BlurTransformation

1.新增依賴

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越大,模糊度越高。