2

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

GDI + 异常中发生一般错误

它是我的代码:

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

1 回答 1

2

试试这个方法:

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))
{
    ...
}
于 2012-12-25T06:41:18.567 回答