Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Drawing.Image to stream C#

Tags:

c#

c#-3.0

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?

like image 902
Linda Avatar asked Nov 03 '09 16:11

Linda


2 Answers

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.

like image 85
JaredPar Avatar answered Oct 07 '22 01:10

JaredPar


Use a memory stream

using(MemoryStream ms = new MemoryStream()) {     image.Save(ms, ...);     return ms.ToArray(); } 
like image 30
John Gietzen Avatar answered Oct 07 '22 01:10

John Gietzen