91

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
  • 42,982
  • 15
  • 99
  • 131
Linda
  • 2,227
  • 5
  • 30
  • 40

4 Answers4

177

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
  • 791
  • 5
  • 21
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • I was just writing that exact same thing! – configurator Nov 03 '09 at 16:34
  • System.Drawing.Image.Save requires a format when saving to a stream. http://msdn.microsoft.com/en-us/library/ms142147.aspx – jcollum May 31 '11 at 20:45
  • 14
    You can preserve the original image format by changing the image save statement to: image.Save(stream, image.RawFormat); – Marko Mar 31 '17 at 16:01
  • When I call `image.Save(stream, image.RawFormat);` it throws a "parameter null" exception for `encoder`, which is weird because I see clearly that there is an overload that only asks for the stream and the format. Is anyone else having this issue? – Joshua Abbott Aug 04 '22 at 17:53
  • The issue of my previous comment is addressed here: https://stackoverflow.com/questions/25242728/image-save-throws-exception-value-cannot-be-null-r-nparameter-name-encoder – Joshua Abbott Aug 04 '22 at 18:01
16

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
2
public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

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

     return stream;
 }
Brett Rigby
  • 6,101
  • 10
  • 46
  • 76
0

Using File Stream

 public Stream ToStream(string imagePath)
    {
    Stream stream=new FileStream(imagePath,FileMode.Open);
    return stream;
    }