簡體   English   中英

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

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

我正在嘗試在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位,但是該代碼對我而言從來沒有用。

有什么建議么?

問題是不允許您創建具有索引像素格式的Graphics對象。

一種解決方案是創建一種不同格式的Graphics對象來進行繪制,並以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;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM