13

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

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

Community
  • 1
  • 1
Christophe Debove
  • 5,868
  • 19
  • 71
  • 121

3 Answers3

35

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
  • 539,124
  • 75
  • 1,126
  • 1,354
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,423
  • 1
  • 29
  • 38
2
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
  • 6,746
  • 3
  • 27
  • 54