前言
最近給自己挖了幾個坑嗅绸,準備填一下。現(xiàn)在來填一下第一個坑:圖片模糊闯参。關于圖片模糊的方法有很多,比如:Open CV 的各種圖片處理悲立、Android 支持的高性能密集型任務執(zhí)行框架 RenderScript、Java 或者 C/C++ 的算法實現(xiàn)圖片模糊處理新博。本篇文章將包含以下內容:
- RenderScript 簡介與圖片模糊的實現(xiàn)
- Java / C++ 算法實現(xiàn)圖片模糊處理
- 一個簡單的動態(tài)模糊實現(xiàn)
- 總結
至于 Open CV 我以前的一些文有些簡單的介紹薪夕,如果只是想模糊圖片就引入整個的 Open CV 個人感覺還是有點“殺雞用牛刀”的感覺。對了赫悄,關于算法實現(xiàn)什么的……我只是個代碼收集者原献,并非我自己實現(xiàn)的馏慨。
開始之前先放個圖,做成什么樣心里有點x數(shù)
如果你看過我同學的那篇Android:簡單靠譜的動態(tài)高斯模糊效果
你一定會發(fā)現(xiàn)我這個布局跟他的有那么一些相似姑隅,哇哈哈哈哈哈写隶,你猜對了,我去他項目里復制的讲仰。當然了慕趴,實現(xiàn)方式不一樣,他是用的 RecyclerView 實現(xiàn)的鄙陡,我這里就自己復寫了 Activity 的 onTouch 實現(xiàn)的動態(tài)模糊冕房。
RenderScript
首先簡單的介紹一下 RenderScript 這里是我讀文檔的翻譯……又到了展現(xiàn)真正的辣雞英語水平的時候了……
RenderScript 是 Android 上的高性能計算密集型任務的框架。雖然串行工作也能受益趁矾,但是RenderScript 主要面向并行數(shù)據(jù)計算耙册。RenderScript 運行時可以跨越設備上可用的處理器如多核CPU和GPU進行并行工作。這讓你可以專注于算法毫捣,而不是調度工作详拙。RenderScript 對于應用進行圖像處理,計算攝影或者計算機視覺等方面特別有用蔓同。
要開始使用RenderScript饶辙,有兩個主要概念應該要理解:
語言本身是為了編寫高性能計算代碼產(chǎn)生的 C99 衍生語言。這篇文章描述了如何使用它去編寫一個計算內核牌柄。
控制 API 是用來管理 RenderScript 資源的生命周期和控制內核運行的畸悬。這套API有三套語言實現(xiàn):Java,Android NDK 的 C++ 和 C99 派生的內核語言本身珊佣。
恩蹋宦,BB這么多,我們只需要有個大致概念就行了咒锻,因為也不是專門去學習這套框架冷冗,我們只是需要使用這套框架的一丁點圖片處理相關的東西而已。千言萬語惑艇,最后就一句話:
RenderScript 是 Android 上的高性能計算密集型任務的框架
行蒿辙,對 RenderScript 有了大致的了解后,可以開始了滨巴,官方文檔里其實有比較詳細的流程思灌,先創(chuàng)建什么 context 啦,然后分配內存巴拉巴拉的拉恭取,不過我這又不是在學RenderScript泰偿,而是想實現(xiàn)一個功能,用完就可以把這框架扔一邊了蜈垮,如果你也是這樣耗跛,不妨直接 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) {
// 計算圖片縮小后的長寬
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
// 將縮小后的圖片作為預渲染的圖片
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
// 創(chuàng)建一張渲染后的輸出圖片
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
// 初始化 RenderScript 上下文
RenderScript rs = RenderScript.create(context);
// 創(chuàng)建一個模糊效果的 RenderScript 的工具對象
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并沒有使用VM來分配內存,所以需要使用Allocation類來創(chuàng)建和分配內存空間裕照。
// 創(chuàng)建Allocation對象的時候其實內存是空的,需要使用copyTo()將數(shù)據(jù)填充進去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 設置渲染的模糊程度, 25f是最大模糊度
blur.setRadius(BLUR_RADIUS);
// 設置blurScript對象的輸入內存
blur.setInput(tmpIn);
// 將輸出數(shù)據(jù)保存到輸出內存中
blur.forEach(tmpOut);
// 將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
運行效果:
Java & C++
這兩種都是采用同一種算法實現(xiàn)的调塌,本質上都是對像素數(shù)組進行處理運算晋南。本來我以為C++的方式會快一些,沒想到在我的mix2上運行反而是Java實現(xiàn)的算法會快一些羔砾。唉负间,真是辣雞C++還不如Java。 當然了……講道理蜒茄,代碼我看了唉擂,就是一樣的,可能是jni的開銷吧檀葛。這里為什么要介紹Javah和C++的算法實現(xiàn)呢玩祟,因為RenderScript雖然文檔上說可以運行在2.3及以上的平臺,但是這個圖片處理的api最低版本是17屿聋。所以說空扎,如果你有需要兼容低版本,還是得采用下別的實現(xiàn)润讥。
這里只放一下Java的實現(xiàn)代碼转锈,因為反而比較快的關系……至于JNI,我這里偷了個懶楚殿,因為以前用CMake項目編譯生成了so撮慨,所以這里直接引用了so。當然了cpp源碼也放在了項目里脆粥,感興趣的可以自己去編譯一下:
/**
* 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)模糊
這里實現(xiàn)的效果圖就是開頭的那張gif了砌溺,首先要明白一點,動態(tài)模糊变隔,不可能每一幀都去調用方法生成一張模糊圖规伐,那樣效率太低了。這里看了別人的思路匣缘,先生成一張模糊圖片猖闪,之后在原來的布局上放上兩個ImageView,一張原圖肌厨,上面的一張是模糊圖培慌,動態(tài)改變上面模糊圖的透明值就能實現(xiàn)動態(tài)透明效果。這想法闊以柑爸,只生成了一次模糊圖片检柬。
這里底部布局我本來是想放一個布局在屏幕外,后來發(fā)現(xiàn)這樣無論怎么滑動都不能把布局滑入『沃罚可能是代碼有問題,也可能是父容器的問題进胯。于是之后就寫了個全屏的布局用爪,但是在界面啟動后將之移動到屏幕外。設置了上下兩塊可點擊將布局滑出的區(qū)域胁镐,在滑動的時候動態(tài)設置模糊圖片控件的alpha值偎血,這樣就實現(xiàn)了動態(tài)模糊,話不多說盯漂,上關鍵代碼:
布局代碼:
<?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;
//獲得當前窗體對象
Window window = this.getWindow();
//設置當前窗體為全屏顯示
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);
}
}
總結
在剛開始的時候我非常的作死颇玷,選用的圖片是1080 * 1920 的,在處理的時候一看內存就缆,我 * 飆到了200多M帖渠,而且處理這張圖片花費了6.6秒左右的時間。我打印了一下這圖片轉化成Bitmap的width和height 分別是
這如果是 ARGB_8888 那么一張圖就是61M竭宰,加上處理需要一個像素數(shù)組空郊,得,另一個61M切揭。剩下在處理像素的時候各種申請的內存飆到200M也不是不可以理解狞甚。本來我想是不是可以使用同一張 Bitmap,在最后setPixels的時候就不用再申請一次內存了廓旬,但是發(fā)現(xiàn)這樣不行哼审,直接報錯了。因為從資源文件拿到的 Bitmap 的 isMutable屬性是false孕豹,不可以直接在原來的 Bitmap 上 setPixels 涩盾。所以原來還需要拷貝一份Bitmap,不過拷貝之后可以將調用 bitmap.recycle() 方法巩步,將之趕緊回收了旁赊。
當然,像我這樣頭鐵硬懟并不好椅野,飆到200M市面上很多手機都會OOM……更好的方式是對縮略圖進行模糊處理终畅。Android里有個縮略圖工具,就幾個方法竟闪,還挺好用的离福,我這里就用的縮略圖工具獲取縮略圖:
public static Bitmap ratio(Bitmap bmp, float pixelW, float pixelH) {
return ThumbnailUtils.extractThumbnail(bmp, (int) pixelW, (int) pixelH);
}
在進行處理前先獲取縮略圖,然后再去處理效率無疑會高非常多炼蛤。
最后妖爷,放上項目地址:https://github.com/ForgetAll/Blur