简体   繁体   中英

image color is becoming inverted when bitmap is converted to byte array and then to memory stream and saved

image color is becoming inverted when bitmap is converted to byte array and then to memory stream and saved. This code was part of the dynamic image creation at my site ommrudraksha.com

 using (var bmp = new System.Drawing.Bitmap(width + 10, height + 10))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.Flush();
                    bmp.Save("ss.jpg");
                 }
            }

Above code saves properly the image.

But when the bmp is converted to memorystream and saved, the background becomes black. Below code generates black image.

            var memStream = new MemoryStream();
            bmp.Save(memStream, ImageFormat.Jpeg);
            var bytes = memStream.ToArray();
            var ms2 = new MemoryStream(bytes);
            Bitmap.FromStream(ms).Save("ss1.jpg");

Let's examine your drawing code first:

bmp.Save("ss.jpg");

In your case, this operation is actually saving as the "PNG" file format, regardless of the file name. I found this out using a hex editor. Windows is smart enough to check the file header, though, so most likely you can still preview or otherwise open it even with a wrong extension name. You can also explicitly specify an output format with a second argument.

By default, a new PNG will also be transparent. Some image formats may default to black, even though they support alpha channel (eg BMP and GIF). This means that if you really want to save as a BMP, you'll have to do some additional processing.


That brings me to why your output image is black. Jpeg does not support transparency at all, so when the transparent PNG was converted, the Jpeg defaulted to black. See this post .

If you need transparency, you'll have to use an image format that supports it. You may also have to clear the entire rectangle first, depending on the format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM