1

recently I started working on my project and unfortunately I have a problem. I want to get sqaures 5x5 from one image, count average color of them and then draw a circle to another Bitmap so I can get a result like this http://imageshack.com/a/img924/9093/ldgQAd.jpg

I have it done, but I can't save to file the Graphics object. I've tried many solutions from Stack, but none of them worked for me.

My code:

//GET IMAGE OBJECT
Image img = Image.FromFile(path);
Image newbmp = new Bitmap(img.Width, img.Height);
Size size = img.Size;

//CREATE NEW BITMAP WITH THIS IMAGE
Bitmap bmp = new Bitmap(img);   

//CREATE EMPTY BITMAP TO DRAW ON IT
Graphics g = Graphics.FromImage(newbmp);

//DRAWING...

//SAVING TO FILE
Bitmap save = new Bitmap(size.Width, size.Height, g);
g.Dispose();
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

The file 'file.bmp' is just a blank image. What am I doing wrong?

1
  • have you tried g.Dispose(); after save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp); ? Commented Feb 8, 2017 at 18:17

1 Answer 1

3

First, your Graphics object should be created from the target bitmap.

Bitmap save = new Bitmap(size.Width, size.Height) ; 
Graphics g = Graphics.FromImage(save );

Second, flush your graphics before Save()

g.Flush() ; 

And last, Dispose() after Save() (or use a using block)

save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
g.Dispose();

It should give you something like this :

Image img = Image.FromFile(path);
Size size = img.Size;

//CREATE EMPTY BITMAP TO DRAW ON IT
using (Bitmap save = new Bitmap(size.Width, size.Height))
{
    using (Graphics g = Graphics.FromImage(save))
    {
        //DRAWING...

        //SAVING TO FILE
        g.Flush();
        save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.