14

Possible Duplicate:
System.Drawing.Image to stream C#

how can I convert a System.Drawing.Image to a stream?

Community
  • 1
  • 1
Christophe Debove
  • 6,088
  • 20
  • 73
  • 124

3 Answers3

39

You can "Save" the image into a stream.

If you need a stream that can be read elsewhere, just create a MemoryStream:

var ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);

// If you're going to read from the stream, you may need to reset the position to the start
ms.Position = 0;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
5

Add a reference to System.Drawing and include the following namespaces:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

And something like this should work:

public Stream GetStream(Image img, ImageFormat format)
{
    var ms = new MemoryStream();
    img.Save(ms, format);
    return ms;
}
heisenberg
  • 9,665
  • 1
  • 30
  • 38
3
MemoryStream memStream = new MemoryStream();
Image.Save(memStream, ImageFormat.Jpeg);

That's how I've done it when I needed to transmit an image in a stream from a web server. (Note you can of course change the format).

The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55