Saving Bitmap drawn on Canvas

◇◆丶佛笑我妖孽 提交于 2019-12-25 02:19:34

问题


In my application I extended the ImageView and overriden its onDraw() method. I am using a color filter to manipulate the bitmap for adding some effects like invert, grayscale etcc. After drawing the bitmap I am trying to save it but I am only able to save the original bitmap with no added effects. Here is the code for onDraw() and save method:

protected void onDraw(Canvas canvas)
{
    Paint paint = mPaint;
    //cmf is the color matrix filter
    paint.setColorFilter(cmf);

    if(mBitmap != null)
    {
        canvas.drawBitmap(mBitmap, offsetW, offsetH, paint);
    }
}

code for saving the bitmap:

 try
        {
            FileOutputStream fout = new FileOutputStream(path);

            mBitmap.compress(CompressFormat.JPEG, 100, fout);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

Am I doing something wrong? Any help will be appretiated.


回答1:


You are painting on the canvas that is displayed, original bitmap is not changed. You should create a new bitmap and paint on it. When color matrix filter changes do this:

Bitmap tmp = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), mBitmap.getConfig())
Canvas canvas = new Canvas(tmp)
cnvas.drawBitmap(tmp, 0, 0, paint);

Then, you can use this tmp bitmap to draw it and save it.

Instead of using customized ImageView use a normal one and set its image to this new bitmap:

imageView.setImageBitmap(tmp)


来源:https://stackoverflow.com/questions/12815694/saving-bitmap-drawn-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!