0

BMP and PNG files are loaded with different pixel formats, even if external tools show 8bpp grayscale for them

Every time when I'm loading 8bits grayscale bmp image to C# Bitmap, it's loaded as 8bit indexed image, somehow c# change pixelformat from 8bits grayscale to 8bits indexed and create gray color pallet.

For PNG images pixel format is changed to 32RGB.

Due to the further processing, they must remain as 8bits greyscale bitmap

        public void LoadFromFile(string filename)
        {
            var bmp = new Bitmap(filename, true);
            Console.WriteLine($"bmp pf = {bmp.PixelFormat.ToString()}");
        }

Maybe there is some way to load that files with correct pixel format? Bitmap constructor do not allow me specify pixelformat

Nedrith
  • 11
  • 1
  • Could you again wirte: 1. what files and in what format you have? 2. how you loading them? 3. What you get in debug? 4. How you are saving them back? 5. What you get(file format of saved image) 6. What you expect? ... because for now *I am trying to load 8bpp grayscale files from disk as bitmap in c#. Files saved as bmp c# load with pixelformat set to 8bppindexed while the same file is saved as png the pixelformat is 32rgb* is just a mess – Selvin Jul 17 '23 at 12:54
  • If you can use WPF there is [PngBitmapDecoder](https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.pngbitmapdecoder?view=windowsdesktop-7.0)/encoder. Just make sure to specify `BitmapCreateOptions.PreservePixelFormat` when creating the decoder. You should also use some third party software to confirm that the files are *actually* saved in 8bpp, since the problem could be in the code to save the file. – JonasH Jul 17 '23 at 12:57
  • This is actually a genuine framework bug. `System.Drawing.Bitmap`'s PNG loading contains a bug that makes it load 8-bit PNG files as 32-bit if they contain a `tRNS` chunk to indicate alpha on the palette. And this even happens if that `tRNS` info marks all indices as fully opaque. See **[How to read 8-bit PNG image as 8-bit PNG image only?](https://stackoverflow.com/q/24074641/395685)**. I'm voting to close this though, since the solution is already posted there. – Nyerguds Jul 18 '23 at 17:06
  • Note that the .Net framework does not contain a specific "8-bit grayscale" format - such files are always treated as 8-bit indexed with a gray fade palette. As far as I know, the png format itself contains no such mode either, anyway. – Nyerguds Jul 24 '23 at 13:40

0 Answers0