我试图用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,代码在图形gImage行抛出异常。我在这里看到了一个解决方案,建议最终的位图可以转换为4位,但这个代码对我来说从来都不起作用。
有什么建议吗?
发布于 2011-01-11 01:46:37
问题是你不能创建一个带有索引像素格式的Graphics对象。
一种解决方案是创建一个不同格式的图形对象来进行绘图,并创建一个PixelFormat.Format4bppIndexed格式的空位图,然后将每个像素从一个图像复制到另一个图像。
发布于 2018-09-17 23:59:22
创建非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;
}
}https://stackoverflow.com/questions/4649688
复制相似问题