简体   繁体   中英

C# - Cannot save bitmap to file

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM