C# - Cannot save bitmap to file

杀马特。学长 韩版系。学妹 提交于 2019-12-23 02:29:24

问题


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


来源:https://stackoverflow.com/questions/42120653/c-sharp-cannot-save-bitmap-to-file

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