Saving Bitmap drawn on Canvas

2.2k views Asked by At

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

There are 1 answers

2
Tomasz Niedabylski On BEST ANSWER

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)