Cryru
Cryru

Reputation: 61

System.Drawing.Image data is different between saving to a file and a stream

I have an image in the png format which I would like to load and convert to a bmp stream. The code I'm using to achieve this is the following:

        // Image.FromFile yields the same result.
        FileStream originalFile = File.Open("image.png", FileMode.Open);
        System.Drawing.Image fileImage = System.Drawing.Image.FromStream(originalFile);

        MemoryStream bmpStream = new MemoryStream();
        fileImage.Save(bmpStream, System.Drawing.Imaging.ImageFormat.Bmp);

Result: https://pastebin.com/raw/p1TBjnD1

However the stream this produces is different from when saving to a file and opening it like this:

        FileStream originalFile = File.Open("image.png", FileMode.Open);
        System.Drawing.Image fileImage = System.Drawing.Image.FromStream(originalFile);

        FileStream bmpStream;
        fileImage.Save("image.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
        bmpStream = File.Open("image.bmp", FileMode.Open);

Result: https://pastebin.com/raw/vSdRwZpL

There appears to be some kind of header missing when saving to a stream. Why is this, and how can I easily add it to my streams without having to save to files?

My question is not how to do this, but why the stream doesn't include this header while the file does.

Upvotes: 2

Views: 1439

Answers (1)

Claudio
Claudio

Reputation: 166

They are not different but when you dump or copy or do something else with memory stream you always have to reset it to its initial position.

fileImage.Save(bmpStream, System.Drawing.Imaging.ImageFormat.Bmp);        
bmpStream.Position = 0
... now you can dump or save to file from bmpStream

If you do not reset the position, you might read nothing back from the MemoryStream. In the case of Image.Save(), it is even more tricky because the Save method puts the MemoryStream position at the beginning of the image data (after the header) assuming this is what you want.

Upvotes: 1

Related Questions