注意:需要版本大于19才可以正常使用
public classBlurImageview {
//圖片縮放比例
private static final floatBITMAP_SCALE=0.2f;
/**
* 模糊圖片的具體方法
*
*@paramcontext上下文對(duì)象
*@parambit需要模糊的圖片
*@return模糊處理后的圖片
*/
public staticBitmapBlurImages(Context context,Bitmap bit, floatblurRadius) {
Bitmap image =ImageCompressL(bit);
// 計(jì)算圖片縮小后的長(zhǎng)寬
intwidth = Math.round(image.getWidth() *BITMAP_SCALE);
intheight = 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è)置渲染的模糊程度, 25f是最大模糊度
blurScript.setRadius(1);
// 設(shè)置blurScript對(duì)象的輸入內(nèi)存
blurScript.setInput(tmpIn);
// 將輸出數(shù)據(jù)保存到輸出內(nèi)存中
try{
// 實(shí)例化Bitmap
blurScript.forEach(tmpOut);
}catch(OutOfMemoryError e) {
//
}
// 將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
returnoutputBitmap;
}
public staticBitmapImageCompressL(Bitmap bitmap) {
doubletargetwidth = Math.sqrt(10.00*1000);
//? ? ? ? if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
// 創(chuàng)建操作圖片用的matrix對(duì)象
Matrix matrix =newMatrix();
// 計(jì)算寬高縮放率
doublex = Math.max(targetwidth / bitmap.getWidth(),targetwidth
/ bitmap.getHeight());
// 縮放圖片動(dòng)作
matrix.postScale((float) x,(float) x);
bitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),
bitmap.getHeight(),matrix, true);
//? ? ? ? }
returnbitmap;
}
}