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

时间:2012-12-25 06:36:12

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

我想保存一张装在图片框中的图片来流式传输。当我以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);
}

1 个答案:

答案 0 :(得分:1)

试试这个方法:

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))
{
    ...
}