我想在图像的顶部和底部添加黑色 Banner . 我可以添加 Banner ,但结果位图的像素格式更改为32位 . 有没有办法得到一个8位位图 . 如上所述here,如果我在构造函数中设置了8位pixelFormat,创建图形将引发异常 . 我读到,如果我从32转换为8,可能像素值将不同于原始像素值 . 使用for循环使用't know if I can create a new bitmap with the desired height and add the black banners'像素 . 任何人都有更好更简单的方法吗?
我的代码如下:
Bitmap img = image as Bitmap;
using (Bitmap bitmap = new Bitmap(img.Width, img.Height + 200*2)) // create blank bitmap of desired size
using (Graphics graphics = Graphics.FromImage(bitmap))
{
SolidBrush brush = new SolidBrush(Color.White);
graphics.FillRectangle(brush, 0, 0, img.Width,200);
// draw existing image onto new blank bitmap
graphics.DrawImage(img, 0, 200, img.Width, img.Height);
// draw your rectangle below the original image
graphics.FillRectangle(brush, 0, 200 + img.Height, img.Width, 200);
// bitmap.Save(@"c:\Test1.bmp");
}
1 回答
这是一个在
bmp8bpp
位图上执行FillRectangle
的例程 .您传入一个索引,如果将使用正数将颜色放入调色板中 . 如果传入负索引,它将尝试找到颜色,如果找不到它,它会将颜色放在索引的末尾 . 这将覆盖之前的任何颜色!
示例调用:
结果:
还有改进的余地:
缺少lockbits中的所有错误检查,包括wrt pixelformat和rectangle data
使用更动态的方案添加颜色可能不错,而不是添加到最后
用于找到调色板中已有的最接近颜色的方案也可能很好
用透明度绘图的方案也很不错 . 为此,必须首先确定所有必要的新颜色;也是透明模式 .
也许应该返回方法中使用的
index
,以便下次调用可以引用它 .对于除矩形以外的其他形状,可以使用复制例程,首先将它们绘制到“普通”32bpp位图上,然后将像素传输到缓冲区 .
Update: 这里有几行要添加(**)或更改(*)以允许绘制 unfilled 矩形;
stroke 0
fills 矩形..: