实现图片高斯模糊

转自 湫水长天 的博客
湫水长天 的博客地址:
http://blog.csdn.net/wl9739

高斯模糊是用的是 Android 的 **RenderScript **,使用 **RenderScript 的渲染效率和使用C/C++ **不相上下,但是使用 **RenderScript **却比使用 **JNI **简单地多!

**RenderScript **官方文档:
https://developer.android.com/guide/topics/renderscript/compute.html

工具类:

public class BlurBitmap {
    /**
     * 图片缩放比例
     */
    private static final float BITMAP_SCALE = 0.4f;
    /**
     * 最大模糊度(0.0到25.0之间)
     */
    private static final float BLUR_RADIUS = 5f;

    /**
     * 模糊方法
     *
     * @param context
     * @param image
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    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);

        //创建一张渲染后的输出图片
        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);

        //设置渲染的模糊程度
        blurScript.setRadius(BLUR_RADIUS);

        //设置blurScript对象的输入内存
        blurScript.setInput(tmpIn);

        //将输出数据保存到输出内存中
        blurScript.forEach(tmpOut);

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

        return outputBitmap;

    }
}

其实 RenderScript 还有其他好多方法的,有兴趣可以看看。

Paste_Image.png

使用方法:

public class RenderScriptActivity extends AppCompatActivity {

    ImageView image;
    //原始图片
    private Bitmap mTempBitmap;
    //处理后的图片
    private Bitmap mFinalBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_render_script);
        image = (ImageView) findViewById(R.id.image);
        //得到原始图片
        mTempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aaa);
        //得到处理后的图片
        mFinalBitmap = BlurBitmap.blur(this, mTempBitmap);
        //把处理后的图片显示出来
        image.setImageBitmap(mFinalBitmap);
    }
}

最后别忘了在 build.gradle 中添加:

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容