C#-无法将位图保存到文件 [英] C# - Cannot save bitmap to file

查看:100
本文介绍了C#-无法将位图保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始从事我的项目,但不幸的是我遇到了问题.我想从一张图像中得到5x5的正方形,计算它们的平均颜色,然后在另一个位图上画一个圆,这样我就可以得到这样的结果

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

我已经完成了,但是我无法保存Graphics对象的文件.我已经尝试过Stack的许多解决方案,但是没有一个对我有用.

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.

我的代码:

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

文件'file.bmp'只是空白图像.我在做什么错了?

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

推荐答案

首先,应从目标位图创建Graphics对象.

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

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

第二,在Save()之前刷新图形

Second, flush your graphics before Save()

g.Flush() ; 

最后,在Save()之后使用Dispose()(或使用using块)

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

这篇关于C#-无法将位图保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆