C# - Cannot save bitmap to file

2019-07-23 19:31发布

问题:

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:

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);
    }
}