十万火急:请大侠们帮助,黑白bmp文件转为单色bmp文件?
因为在做小票打印机的项目,遇到一个困难。小票打印机只支持单色bmp图片的打印。
现在问题将一张黑白bmp图片转为单色bmp文件。在网上也找了很多资料,但都没有好的代码。
希望大拿们能帮忙解决一下。十万火急。多谢各位。以下有一段代码,但生成的结果不清楚。
供大家参考一下。另外提供一张源图。开发语言为c#。
另外我用系统自带的画图软件转换为单色bmp可以实现,但需要程序进行自动处理。
有没有大侠写段代码调用画图软件自动转换一下。
private void button8_Click(object sender, EventArgs e)
{
int v = 8;
Bitmap matrix = (Bitmap)Image.FromFile("e:\\m1_1.bmp");
int width = matrix.Width;
int height = matrix.Height;
Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int sWidth = Math.Abs(bmpData.Stride);
int sDepth = 8;
int bytes = sWidth * bmp.Height;
System.Diagnostics.Debug.WriteLine(string.Format("宽度:{0},1个字符等于{1}像素", sWidth, sDepth));
System.Diagnostics.Debug.WriteLine(string.Format("文件大小:{0}", bytes));
byte[] rgbValues = new byte[bytes];
int r, g, b;
int sColor = 0;
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
for (int h = 0; h < bmp.Height; h++)
{
for (int w = 0; w < sWidth; w++)
{
sColor = 0;
for (int i = 0; i < sDepth; i++)
{
if ((i + w * sDepth) >= bmp.Width)
{
break;
}
r = matrix.GetPixel(i + w * sDepth, h).R;
g = matrix.GetPixel(i + w * sDepth, h).G;
b = matrix.GetPixel(i + w * sDepth, h).B;
sColor += (byte)(((byte)(0.2125 * r + 0.7154 * g + 0.0721 * b) >= v) ? (128 >> (i)) : 0);
}
rgbValues[sWidth * h + w] = (byte)sColor;
}
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
bmp.UnlockBits(bmpData);
bmp.Save("e:\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
[解决办法]
不管阀值为几,lz也没有需要像程序中那样“先变为模糊图形再二值化(黑白化)”。因此“各个点想加,然后除以9”完全是错误的。
另外,lz本来就有一个黑白图,只不过是要逐点变为单色的彩色图。不是别的要求。
还是重写程序吧。
[解决办法]
已经发送。查收一下。我用的VS2012,如果你没有这么高的版本,你就把代码复制一样,你应该懂的。