88

I have a System.Drawing.Image in my program. The file is not on the file system it is being held in memory. I need to create a stream from it. How would I go about doing this?

mauris
  • 41,504
  • 15
  • 94
  • 130
Linda
  • 2,187
  • 5
  • 29
  • 40

3 Answers3

171

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

Kristian Frost
  • 781
  • 5
  • 21
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
16

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}
John Gietzen
  • 47,524
  • 30
  • 142
  • 185
2
public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }
Brett Rigby
  • 5,666
  • 10
  • 44
  • 74