MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Why can't I create an image from image array

I'm getting an error very similar to A generic error occurred in GDI+, JPEG Image to MemoryStream

However, I don't believe I'm shutting down the stream and as such, the answers don't apply

Please consider

var img = (Tests.Properties.Resources.image).ToByteArray(); //img is a png;

using (var ms = new MemoryStream(img))
{
    var pic = Image.FromStream(ms);
    pic.Save(this._absolutePath, this._format); //kaboomn
}

The issue is the final line of code goes kaboom!

"A generic error occurred in GDI+."

This is the extension method

public static byte[] ToByteArray(this Bitmap image)
{
    using (var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}

So, although I'm using 2 streams, the first time returns the bytes and as such, I'm not using the same stream, I'm simply working with the bytes.

Upvotes: 1

Views: 107

Answers (1)

Sherif Ahmed
Sherif Ahmed

Reputation: 1946

replace

using (var ms = new MemoryStream(img))
{
    var pic = Image.FromStream(ms);
    pic.Save(this._absolutePath, this._format);
}

to

var pic = Image.FromStream(new MemoryStream(img)));
pic.Save(this._absolutePath, this._format);

Check this Bitmap and Image constructor dependencies

Upvotes: 1

Related Questions