Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a System.Drawing.Image to a stream [duplicate]

Tags:

c#

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

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

like image 487
Christophe Debove Avatar asked Jun 27 '11 18:06

Christophe Debove


3 Answers

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;
like image 68
Reed Copsey Avatar answered Nov 11 '22 16:11

Reed Copsey


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;
}
like image 5
heisenberg Avatar answered Nov 11 '22 16:11

heisenberg


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).

like image 3
The Evil Greebo Avatar answered Nov 11 '22 17:11

The Evil Greebo