【问题标题】:RenderScript blur overrides the original BitmapRenderScript 模糊覆盖原始位图
【发布时间】:2016-05-05 08:19:57
【问题描述】:

我正在尝试使用 RenderScript 创建一个模糊位图,以将其设置为包含 ImageViewLinearLayout 的背景。我还想要一个清晰的位图原始副本,以便我可以将其设置为 ImageView 中的图像。

这是我的代码:

ImageView mainImage;

Bitmap mainBMP, blurredBMP

LinearLayout background;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_work_area);

    getImage(); // obtain bitmap from file
    mainImage.setImageBitmap(mainBMP); // set the original bitmap in imageview 

    // create a blurred bitmap drawable and set it as background for linearlayout
    BitmapDrawable drawable = new BitmapDrawable(getResources(), blur(mainBMP)); 
    mainBackground.setBackground(drawable); 


    registerForContextMenu(objectImage);
    registerForContextMenu(textArea);

}

private void getImage(){
    String filename = getIntent().getStringExtra("image");
    try {
        FileInputStream is = this.openFileInput(filename);
        mainBMP = BitmapFactory.decodeStream(is);
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@TargetApi(17)
public Bitmap blur(Bitmap image) {
    if (null == image) return null;

    Bitmap outputBitmap = Bitmap.createBitmap(image);
    final RenderScript renderScript = RenderScript.create(this);
    Allocation tmpIn = Allocation.createFromBitmap(renderScript, image);
    Allocation tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap);

    //Intrinsic Gausian blur filter
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
    theIntrinsic.setRadius(BLUR_RADIUS);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);
    return outputBitmap;
}

这就是我想要的最终结果:

但这就是我得到的:

那么我如何制作两个副本同一个位图,其中一个模糊,另一个清晰且原始

【问题讨论】:

    标签: java android bitmap blur renderscript


    【解决方案1】:

    问题在于如何创建输出位图。您正在使用基于输入 Bitmap 对象为您提供不可变 Bitmap 对象的调用。更改此行:

    Bitmap outputBitmap = Bitmap.createBitmap(image);
    

    变成这样:

    Bitmap outputBitmap = image.copy(image.getConfig(), true);
    

    这将为您提供一个单独的 Bitmap 对象,它是原始和可变的副本。现在 Renderscript 确实在修改原始文件(尽管它确实应该失败,因为 outputBitmap 是不可变的。

    【讨论】:

    • 做到了!谢谢。
    • 太好了,很高兴听到它!
    • 第一个位图不是从图片创建的怎么办?我的来自decodeStream
    • @hippietrail 没关系。结果Bitmap(只要它有效)将由位图工厂正确设置其配置。只要您的 RS 理解此输入并期望产生相同类型的输出(宽度/高度、每像素位数等),那么您应该能够使用相同的技术。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多