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?
Asked
Active
Viewed 1.1e+01k times
3 Answers
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
-
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
-
13You 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
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