首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android实现Bitmap高斯模糊效果

Android实现Bitmap高斯模糊效果

作者头像
程序员飞飞
发布2020-02-27 16:09:10
1.5K0
发布2020-02-27 16:09:10
举报
文章被收录于专栏:Android&Java技术Android&Java技术

Android实现Bitmap高斯模糊效果

自定义高斯模糊工具类

import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

/**
 * Created by xpf on 2017/6/24 :)
 * Function:实现高斯模糊工具类
 */

public class BlurBitmapUtil {

    // 图片缩放比例(即模糊度)
    private static final float BITMAP_SCALE = 0.4f;

    /**
     * @param context 上下文对象
     * @param image   需要模糊的图片
     * @return 模糊处理后的Bitmap
     */
    public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius) {
        // 计算图片缩小后的长宽
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        // 将缩小后的图片做为预渲染的图片
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        // 创建一张渲染后的输出图片
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        // 创建RenderScript内核对象
        RenderScript rs = RenderScript.create(context);
        // 创建一个模糊效果的RenderScript的工具对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

        // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间
        // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);

        // 设置渲染的模糊程度, 25f是最大模糊度
        blurScript.setRadius(blurRadius);
        // 设置blurScript对象的输入内存
        blurScript.setInput(tmpIn);
        // 将输出数据保存到输出内存中
        blurScript.forEach(tmpOut);

        // 将数据填充到Allocation中
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }
}

使用示例

    if (image != null) {
        Bitmap blurBitmap = BlurBitmapUtil.blurBitmap(mContext, image, 20);
        blurView.setImageBitmap(blurBitmap);
        } else {
            // 如果image为null就设置一张本地默认的模糊照片
            blurView.setImageResource(R.drawable.img_mohu);
        }

Thanks all.

Good night~

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-07-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Android实现Bitmap高斯模糊效果
    • 自定义高斯模糊工具类
      • 使用示例
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档