c# - 以流格式保存图片框中的图像

标签 c# c#-4.0 c#-2.0

我想保存加载到图片框中的图片以进行流式传输。当我以 png 格式保存时,它可以正常工作,但是当我想以其他格式保存时,我得到

A Generic error occured in GDI + exception

这是我的代码:

Image Img = pictureBox1.Image;
byte[] inputImage = new byte[Img.Width * Img.Height];
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Read(inputImage, 0, Img.Width * Img.Height);

if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(Img.RawFormat))
{
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(Img.RawFormat))
{
    ms.Seek(0, SeekOrigin.Begin);
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
}
else if (System.Drawing.Imaging.ImageFormat.Png.Equals(Img.RawFormat))
{
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(Img.RawFormat))
{
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
}

最佳答案

试试这个方法:

public Stream ImageToStream(Image image, System.Drawing.Imaging.ImageFormat format)
{
    MemoryStream ms = new MemoryStream();
    image.Save(ms, format);
    return  ms;
}

并使用它:

using(Stream stream = ImageToStream(pictureBox1.Image, 
                           System.Drawing.Imaging.ImageFormat.Gif))
{
    ...
}

关于c# - 以流格式保存图片框中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028315/

相关文章:

c# - 如何在Windows Phone 7 中使用SQLite 数据库?

.net - 如何使用代码添加自定义 BizTalk 持久点?

c# - 最佳实践 : How to expose a read-only ICollection

c# - 为什么我不应该总是在 C# 中使用可空类型

C#:我怎样才能优雅和/或简单地进行跨线程调用?

c# - 在 LINQ 中加入列并运行包含运算符

c# - WCF 数据集压缩

c# - response.write 编码错误

file-upload - 2 GB 文件在 C# 中上传

C# JSON 字符串反序列化