简体   繁体   中英

How to prevent VS to set to 32ARGB the Bitmap from a 8 bpp original image

Add a 8 bpp PNG to your resources file. If you try to use it, like:

Bitmap bmp = properties.Resources.My8bppImage;

The bmp PixelFormat will be 32 ARGB ! But it is wrong, it should be 8 bpp indexed. How to get the correct Bitmap?

You don't have a lot of options here, both the Visual Studio resource editor and the Bitmap class use a PNG decoder that will convert the image to 32bpp. This is meant to be helpful, 32bpp renders nice and quick.

The fallback option is to use the System.Windows.Media.Imaging.PngBitmapDecoder class. You can pass it the BitmapCreateOptions.PreservePixelFormat option and force it to keep the 8bpp format. You can add the png as a resource by renaming it first to, say, a .bin file so it doesn't try to interpret it as an image file but makes it a byte[]. Then code like this will work:

using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
...
        Stream stream = new MemoryStream(Properties.Resources.marble8);
        PngBitmapDecoder decoder = new PngBitmapDecoder(stream, 
            BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bitmapSource = decoder.Frames[0];

Where "marble8" was the test image I used, substitute your own. You'll need to add references to the WindowsBase and PresentationCore assemblies.

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