jac
jac

Reputation: 9726

Convert a byte[] to Image without using a MemoryStream

I am having a problem exporting SQL images to files. I first initialize a List. MyRecord is a class with GraphicName, and Graphic properties. When I try to go through the list and save MyRecord.Graphic to disk I get a first chance exception of type 'System.ObjectDisposedException'. I realize this is because when I converted the bytes from the database to an Image I used a using statement with the MemoryStream. I can not use the using statement and it all works, but I am worried about memory usage / memory leaks on up to 6,000 records. Is there another way to convert the bytes to an image or is there a better design to do this?

... prior code
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
    while (reader.Read())
    {
        MyRecord record = new MyRecord();
        record.GraphicId = reader["GRAPHIC_ID"].ToString();
        record.Graphic = !reader.IsDBNull(reader.GetOrdinal("IMAGE")) ? GetImage((byte[])reader["IMAGE"]) : null;
        records.Add(record);
    }
... more code

private Image GetImage(byte[] rawImage)
{
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(rawImage))
    {
        Image image = Image.FromStream(ms);
        return image;
    }
}

Upvotes: 0

Views: 2027

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499800

You shouldn't use a using statement with a stream that will be passed to Image.FromStream, as the Image class is basically responsible for the stream from then on. From the documentation:

You must keep the stream open for the lifetime of the Image.

Just change your code to:

private Image GetImage(byte[] rawImage)
{
    var stream = new MemoryStream(rawImage);
    return Image.FromStream(stream);
}

... but then make sure you dispose of your Image objects later. That will dispose of the stream, allowing the memory to be garbage collected. Then there shouldn't be any memory leaks - but you need to work out whether you can really load all 6000 images into memory at a time anyway.

(If you don't dispose of the Image objects, they're likely to be finalized anyway at some point - but it would be better to dispose of them deterministically.)

Upvotes: 6

Related Questions