前言
最近給自己挖了幾個(gè)坑,準(zhǔn)備填一下?,F(xiàn)在來填一下第一個(gè)坑:圖片模糊。關(guān)于圖片模糊的方法有很多,比如:Open CV 的各種圖片處理、Android 支持的高性能密集型任務(wù)執(zhí)行框架 RenderScript、Java 或者 C/C++ 的算法實(shí)現(xiàn)圖片模糊處理。本篇文章將包含以下內(nèi)容:
- RenderScript 簡介與圖片模糊的實(shí)現(xiàn)
- Java / C++ 算法實(shí)現(xiàn)圖片模糊處理
- 一個(gè)簡單的動態(tài)模糊實(shí)現(xiàn)
- 總結(jié)
至于 Open CV 我以前的一些文有些簡單的介紹,如果只是想模糊圖片就引入整個(gè)的 Open CV 個(gè)人感覺還是有點(diǎn)“殺雞用牛刀”的感覺。對了,關(guān)于算法實(shí)現(xiàn)什么的……我只是個(gè)代碼收集者,并非我自己實(shí)現(xiàn)的。
開始之前先放個(gè)圖,做成什么樣心里有點(diǎn)x數(shù)

如果你看過我同學(xué)的那篇Android:簡單靠譜的動態(tài)高斯模糊效果
你一定會發(fā)現(xiàn)我這個(gè)布局跟他的有那么一些相似,哇哈哈哈哈哈,你猜對了,我去他項(xiàng)目里復(fù)制的。當(dāng)然了,實(shí)現(xiàn)方式不一樣,他是用的 RecyclerView 實(shí)現(xiàn)的,我這里就自己復(fù)寫了 Activity 的 onTouch 實(shí)現(xiàn)的動態(tài)模糊。
RenderScript
首先簡單的介紹一下 RenderScript 這里是我讀文檔的翻譯……又到了展現(xiàn)真正的辣雞英語水平的時(shí)候了……
RenderScript 是 Android 上的高性能計(jì)算密集型任務(wù)的框架。雖然串行工作也能受益,但是RenderScript 主要面向并行數(shù)據(jù)計(jì)算。RenderScript 運(yùn)行時(shí)可以跨越設(shè)備上可用的處理器如多核CPU和GPU進(jìn)行并行工作。這讓你可以專注于算法,而不是調(diào)度工作。RenderScript 對于應(yīng)用進(jìn)行圖像處理,計(jì)算攝影或者計(jì)算機(jī)視覺等方面特別有用。
要開始使用RenderScript,有兩個(gè)主要概念應(yīng)該要理解:
語言本身是為了編寫高性能計(jì)算代碼產(chǎn)生的 C99 衍生語言。這篇文章描述了如何使用它去編寫一個(gè)計(jì)算內(nèi)核。
控制 API 是用來管理 RenderScript 資源的生命周期和控制內(nèi)核運(yùn)行的。這套API有三套語言實(shí)現(xiàn):Java,Android NDK 的 C++ 和 C99 派生的內(nèi)核語言本身。
恩,BB這么多,我們只需要有個(gè)大致概念就行了,因?yàn)橐膊皇菍iT去學(xué)習(xí)這套框架,我們只是需要使用這套框架的一丁點(diǎn)圖片處理相關(guān)的東西而已。千言萬語,最后就一句話:
RenderScript 是 Android 上的高性能計(jì)算密集型任務(wù)的框架
行,對 RenderScript 有了大致的了解后,可以開始了,官方文檔里其實(shí)有比較詳細(xì)的流程,先創(chuàng)建什么 context 啦,然后分配內(nèi)存巴拉巴拉的拉,不過我這又不是在學(xué)RenderScript,而是想實(shí)現(xiàn)一個(gè)功能,用完就可以把這框架扔一邊了,如果你也是這樣,不妨直接 copy 下面的代碼:
/**
* 圖片縮放比例
*/
private static final float BITMAP_SCALE = 0.4f;
/**
* 最大模糊度(在0.0到25.0之間)
*/
private static final float BLUR_RADIUS = 25f;
public static Bitmap blur(Context context, Bitmap image) {
// 計(jì)算圖片縮小后的長寬
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);
// 初始化 RenderScript 上下文
RenderScript rs = RenderScript.create(context);
// 創(chuàng)建一個(gè)模糊效果的 RenderScript 的工具對象
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并沒有使用VM來分配內(nèi)存,所以需要使用Allocation類來創(chuàng)建和分配內(nèi)存空間。
// 創(chuàng)建Allocation對象的時(shí)候其實(shí)內(nèi)存是空的,需要使用copyTo()將數(shù)據(jù)填充進(jìn)去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 設(shè)置渲染的模糊程度, 25f是最大模糊度
blur.setRadius(BLUR_RADIUS);
// 設(shè)置blurScript對象的輸入內(nèi)存
blur.setInput(tmpIn);
// 將輸出數(shù)據(jù)保存到輸出內(nèi)存中
blur.forEach(tmpOut);
// 將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
運(yùn)行效果:

Java & C++
這兩種都是采用同一種算法實(shí)現(xiàn)的,本質(zhì)上都是對像素?cái)?shù)組進(jìn)行處理運(yùn)算。本來我以為C++的方式會快一些,沒想到在我的mix2上運(yùn)行反而是Java實(shí)現(xiàn)的算法會快一些。唉,真是辣雞C++還不如Java。 當(dāng)然了……講道理,代碼我看了,就是一樣的,可能是jni的開銷吧。這里為什么要介紹Javah和C++的算法實(shí)現(xiàn)呢,因?yàn)镽enderScript雖然文檔上說可以運(yùn)行在2.3及以上的平臺,但是這個(gè)圖片處理的api最低版本是17。所以說,如果你有需要兼容低版本,還是得采用下別的實(shí)現(xiàn)。
這里只放一下Java的實(shí)現(xiàn)代碼,因?yàn)榉炊容^快的關(guān)系……至于JNI,我這里偷了個(gè)懶,因?yàn)橐郧坝肅Make項(xiàng)目編譯生成了so,所以這里直接引用了so。當(dāng)然了cpp源碼也放在了項(xiàng)目里,感興趣的可以自己去編譯一下:
/**
* StackBlur By Java Bitmap
*
* @param bmp bmp Image
* @param radius Blur radius
* @return Image Bitmap
*/
public static Bitmap blurInJava(Bitmap bmp, int radius) {
// Stack Blur v1.0 from
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the image. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
if (radius < 1) {
return (null);
}
Bitmap bitmap = ratio(bmp, bmp.getWidth() * BITMAP_SCALE, bmp.getHeight() * BITMAP_SCALE);
// Bitmap bitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
// Return this none blur
if (radius == 1) {
return bitmap;
}
bmp.recycle();
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
// get array
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
// run Blur
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
short r[] = new short[wh];
short g[] = new short[wh];
short b[] = new short[wh];
int rSum, gSum, bSum, x, y, i, p, yp, yi, yw;
int vMin[] = new int[Math.max(w, h)];
int divSum = (div + 1) >> 1;
divSum *= divSum;
short dv[] = new short[256 * divSum];
for (i = 0; i < 256 * divSum; i++) {
dv[i] = (short) (i / divSum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackPointer;
int stackStart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routSum, goutSum, boutSum;
int rinSum, ginSum, binSum;
for (y = 0; y < h; y++) {
rinSum = ginSum = binSum = routSum = goutSum = boutSum = rSum = gSum = bSum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rSum += sir[0] * rbs;
gSum += sir[1] * rbs;
bSum += sir[2] * rbs;
if (i > 0) {
rinSum += sir[0];
ginSum += sir[1];
binSum += sir[2];
} else {
routSum += sir[0];
goutSum += sir[1];
boutSum += sir[2];
}
}
stackPointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rSum];
g[yi] = dv[gSum];
b[yi] = dv[bSum];
rSum -= routSum;
gSum -= goutSum;
bSum -= boutSum;
stackStart = stackPointer - radius + div;
sir = stack[stackStart % div];
routSum -= sir[0];
goutSum -= sir[1];
boutSum -= sir[2];
if (y == 0) {
vMin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vMin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinSum += sir[0];
ginSum += sir[1];
binSum += sir[2];
rSum += rinSum;
gSum += ginSum;
bSum += binSum;
stackPointer = (stackPointer + 1) % div;
sir = stack[(stackPointer) % div];
routSum += sir[0];
goutSum += sir[1];
boutSum += sir[2];
rinSum -= sir[0];
ginSum -= sir[1];
binSum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinSum = ginSum = binSum = routSum = goutSum = boutSum = rSum = gSum = bSum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rSum += r[yi] * rbs;
gSum += g[yi] * rbs;
bSum += b[yi] * rbs;
if (i > 0) {
rinSum += sir[0];
ginSum += sir[1];
binSum += sir[2];
} else {
routSum += sir[0];
goutSum += sir[1];
boutSum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackPointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rSum] << 16) | (dv[gSum] << 8) | dv[bSum];
rSum -= routSum;
gSum -= goutSum;
bSum -= boutSum;
stackStart = stackPointer - radius + div;
sir = stack[stackStart % div];
routSum -= sir[0];
goutSum -= sir[1];
boutSum -= sir[2];
if (x == 0) {
vMin[y] = Math.min(y + r1, hm) * w;
}
p = x + vMin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinSum += sir[0];
ginSum += sir[1];
binSum += sir[2];
rSum += rinSum;
gSum += ginSum;
bSum += binSum;
stackPointer = (stackPointer + 1) % div;
sir = stack[stackPointer];
routSum += sir[0];
goutSum += sir[1];
boutSum += sir[2];
rinSum -= sir[0];
ginSum -= sir[1];
binSum -= sir[2];
yi += w;
}
}
// set Bitmap
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}

動態(tài)模糊
這里實(shí)現(xiàn)的效果圖就是開頭的那張gif了,首先要明白一點(diǎn),動態(tài)模糊,不可能每一幀都去調(diào)用方法生成一張模糊圖,那樣效率太低了。這里看了別人的思路,先生成一張模糊圖片,之后在原來的布局上放上兩個(gè)ImageView,一張?jiān)瓐D,上面的一張是模糊圖,動態(tài)改變上面模糊圖的透明值就能實(shí)現(xiàn)動態(tài)透明效果。這想法闊以,只生成了一次模糊圖片。
這里底部布局我本來是想放一個(gè)布局在屏幕外,后來發(fā)現(xiàn)這樣無論怎么滑動都不能把布局滑入??赡苁谴a有問題,也可能是父容器的問題。于是之后就寫了個(gè)全屏的布局,但是在界面啟動后將之移動到屏幕外。設(shè)置了上下兩塊可點(diǎn)擊將布局滑出的區(qū)域,在滑動的時(shí)候動態(tài)設(shè)置模糊圖片控件的alpha值,這樣就實(shí)現(xiàn)了動態(tài)模糊,話不多說,上關(guān)鍵代碼:
布局代碼:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_img"
android:src="@drawable/test"
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/iv_blur_img"
android:scaleType="fitXY"
android:alpha="0"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="@+id/rl_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_tem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:fontFamily="sans-serif-thin"
android:gravity="bottom"
android:text="37°"
android:textColor="@android:color/white"
android:textSize="90sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="36dp"
android:background="#44000000"
android:orientation="vertical"
android:paddingLeft="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="WeatherInfo"
android:textColor="@android:color/white"
android:textSize="24sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Show more info"
android:textColor="@android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="36dp"
android:background="#44000000"
android:orientation="vertical"
android:paddingLeft="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="WeatherInfo"
android:textColor="@android:color/white"
android:textSize="24sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Show more info"
android:textColor="@android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="36dp"
android:background="#44000000"
android:orientation="vertical"
android:paddingLeft="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="WeatherInfo"
android:textColor="@android:color/white"
android:textSize="24sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Show more info"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Activity代碼:
package com.xiasuhuei321.blur;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.xiasuhuei321.gank_kotlin.ImageProcess;
/**
* Created by xiasuhuei321 on 2017/10/15.
* author:luo
* e-mail:xiasuhuei321@163.com
*/
public class DynamicBlurActivity extends AppCompatActivity {
private ImageView blurImg;
private int height;
private View container;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
//獲得當(dāng)前窗體對象
Window window = this.getWindow();
//設(shè)置當(dāng)前窗體為全屏顯示
window.setFlags(flag, flag);
setContentView(R.layout.activity_dynamic_blur);
initView();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
height = wm.getDefaultDisplay().getHeight();
}
private void initView() {
blurImg = (ImageView) findViewById(R.id.iv_blur_img);
blurImg.setImageBitmap(ImageProcess.blur(this,
BitmapFactory.decodeResource(getResources(), R.drawable.test)));
container = findViewById(R.id.rl_container);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
container.setTranslationY(height + 100);
}
}, 100);
}
float y;
boolean scrollFlag = false;
float sumY = 0;
boolean isShow = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
y = event.getY();
if (y > height * 0.9) {
scrollFlag = true;
} else if (y < height * 0.1) {
if (!isShow) return false;
scrollFlag = true;
}
break;
case MotionEvent.ACTION_MOVE:
sumY = event.getY() - y;
if (scrollFlag) {
container.setTranslationY(event.getY());
if (!isShow) blur(sumY);
else reverseBlur(sumY);
}
Log.e("DynamicBlurActivity", "滾動sumY值:" + sumY + " scrollFlag:" + scrollFlag);
break;
case MotionEvent.ACTION_UP:
if(scrollFlag) {
if (Math.abs(sumY) > height * 0.5) {
if (isShow) hide();
else show();
} else {
if (isShow) show();
else hide();
}
sumY = 0;
}
scrollFlag = false;
break;
}
return true;
}
private void hide() {
container.setTranslationY(height + 100);
blur(0);
isShow = false;
}
private void show() {
container.setTranslationY(0);
blur(1000);
isShow = true;
}
private void blur(float sumY) {
float absSum = Math.abs(sumY);
float alpha = absSum / 1000;
if (alpha > 1) alpha = 1;
blurImg.setAlpha(alpha);
}
private void reverseBlur(float sumY) {
float absSum = Math.abs(sumY);
float alpha = absSum / 1000;
if (alpha > 1) alpha = 1;
blurImg.setAlpha(1 - alpha);
}
}
總結(jié)
在剛開始的時(shí)候我非常的作死,選用的圖片是1080 * 1920 的,在處理的時(shí)候一看內(nèi)存,我 * 飆到了200多M,而且處理這張圖片花費(fèi)了6.6秒左右的時(shí)間。我打印了一下這圖片轉(zhuǎn)化成Bitmap的width和height 分別是

這如果是 ARGB_8888 那么一張圖就是61M,加上處理需要一個(gè)像素?cái)?shù)組,得,另一個(gè)61M。剩下在處理像素的時(shí)候各種申請的內(nèi)存飆到200M也不是不可以理解。本來我想是不是可以使用同一張 Bitmap,在最后setPixels的時(shí)候就不用再申請一次內(nèi)存了,但是發(fā)現(xiàn)這樣不行,直接報(bào)錯(cuò)了。因?yàn)閺馁Y源文件拿到的 Bitmap 的 isMutable屬性是false,不可以直接在原來的 Bitmap 上 setPixels 。所以原來還需要拷貝一份Bitmap,不過拷貝之后可以將調(diào)用 bitmap.recycle() 方法,將之趕緊回收了。
當(dāng)然,像我這樣頭鐵硬懟并不好,飆到200M市面上很多手機(jī)都會OOM……更好的方式是對縮略圖進(jìn)行模糊處理。Android里有個(gè)縮略圖工具,就幾個(gè)方法,還挺好用的,我這里就用的縮略圖工具獲取縮略圖:
public static Bitmap ratio(Bitmap bmp, float pixelW, float pixelH) {
return ThumbnailUtils.extractThumbnail(bmp, (int) pixelW, (int) pixelH);
}
在進(jìn)行處理前先獲取縮略圖,然后再去處理效率無疑會高非常多。
最后,放上項(xiàng)目地址:https://github.com/ForgetAll/Blur