首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用C#创建4位PNG?

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

Stack Overflow用户
提问于 2011-01-11 01:41:32
回答 2查看 1.5K关注 0票数 2

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

代码如下:

代码语言:javascript
复制
 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,代码在图形gImage行抛出异常。我在这里看到了一个解决方案,建议最终的位图可以转换为4位,但这个代码对我来说从来都不起作用。

有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-11 01:46:37

问题是你不能创建一个带有索引像素格式的Graphics对象。

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

票数 1
EN

Stack Overflow用户

发布于 2018-09-17 23:59:22

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

代码语言:javascript
复制
    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;
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4649688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档