Linda
Linda

Reputation: 2247

System.Drawing.Image to stream C#

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?

Upvotes: 92

Views: 133052

Answers (4)

user18517924
user18517924

Reputation:

Using FileStream:

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

Upvotes: 0

Brett Rigby
Brett Rigby

Reputation: 6216

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 754665

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.

Upvotes: 180

John Gietzen
John Gietzen

Reputation: 49544

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

Upvotes: 16

Related Questions