简体   繁体   English

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

[英]How can I create a 4-bit PNG with C#?

I am trying to create a 4-bit PNG file in C# but my code does not work. 我正在尝试在C#中创建4位PNG文件,但是我的代码无法正常工作。

Here is the code: 这是代码:

 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);

The code throws an exception at Graphics gImage line due to PixelFormat set to Format4bppIndexed. 由于PixelFormat设置为Format4bppIndexed,因此代码在Graphics gImage行上引发了异常。 I saw a solution here suggesting that the final bitmap can be converted to 4-bit, but that code never worked for me. 我在这里看到了一个解决方案,建议可以将最终位图转换为4位,但是该代码对我而言从来没有用。

Any suggestions? 有什么建议么?

The problem is that you aren't allowed to create a Graphics object with an indexed pixel format. 问题是不允许您创建具有索引像素格式的Graphics对象。

One solution would be to create a Graphics object in a different format to do your drawing, and create an empty Bitmap in PixelFormat.Format4bppIndexed format, and copy each pixel from one image to the other. 一种解决方案是创建一种不同格式的Graphics对象来进行绘制,并以PixelFormat.Format4bppIndexed格式创建一个空的位图,然后将每个像素从一个图像复制到另一个图像。

Create a non-4bit, and then convert to 4bit using the System.Windows.Media.Imaging library: 创建一个非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;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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