如何使用C#创建4位PNG?

如何使用C#创建4位PNG?,c#,png,C#,Png,我试图用C#创建一个4位PNG文件,但我的代码不起作用 代码如下: Bitmap bmp = new Bitmap(200, 50, PixelFormat.Format4bppIndexed); string f = bmp.PixelFormat.ToString(); Graphics gImage = Graphics.FromImage(bmp); gImage.FillRectangle(Brushes.Red, 0, 0, bmp.Width - 20, bmp.Heigh

我试图用C#创建一个4位PNG文件,但我的代码不起作用

代码如下:

 Bitmap bmp = new Bitmap(200, 50, PixelFormat.Format4bppIndexed);
 string f = bmp.PixelFormat.ToString();
 Graphics gImage = Graphics.FromImage(bmp);
 gImage.FillRectangle(Brushes.Red, 0, 0, bmp.Width - 20, bmp.Height - 20);
 gImage.DrawRectangle(Pens.White, 0, 0, bmp.Width - 20, bmp.Height - 20);
 gImage.DrawString("Test", SystemFonts.DefaultFont, Brushes.White, 5, 8);
 bmp.Save("C:\\buttons_normal1.png",ImageFormat.Png);
由于PixelFormat设置为Format4bppIndexed,代码在Graphics gImage行引发异常。我在这里看到了一个解决方案,建议最终的位图可以转换为4位,但这段代码对我来说从来都不起作用


有什么建议吗?

问题是不允许您使用索引像素格式创建图形对象


一种解决方案是以不同的格式创建图形对象以进行绘图,并以PixelFormat.Format4bppIndexed格式创建一个空位图,然后将每个像素从一个图像复制到另一个图像。

创建一个非4位,然后使用System.Windows.Media.Imaging库转换为4位:

    public void to4bit(Bitmap sourceBitmap, Stream outputStream)
    {
        BitmapImage myBitmapImage = ToBitmapImage(sourceBitmap);
        FormatConvertedBitmap fcb = new FormatConvertedBitmap();
        fcb.BeginInit();
        myBitmapImage.DecodePixelWidth = sourceBitmap.Width;
        fcb.Source = myBitmapImage;
        fcb.DestinationFormat = System.Windows.Media.PixelFormats.Gray4;
        fcb.EndInit();

        PngBitmapEncoder bme = new PngBitmapEncoder();
        bme.Frames.Add(BitmapFrame.Create(fcb));
        bme.Save(outputStream);

    }

    private BitmapImage ToBitmapImage(Bitmap sourceBitmap)
    {
        using (var memory = new MemoryStream())
        {
            sourceBitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();

            return bitmapImage;
        }
    }

@Mert-您可以使用Bitmap.GetPixel和Bitmap.SetPixel读取和写入单个像素,但这可能非常慢。更快的方法是使用锁位直接访问内存中的像素数据。鲍勃·鲍威尔是这方面的优秀资源: