按颜色为条码位图着色
Colorize barcode bitmap by Color
我正在使用 ZXing.NET 和此代码
生成条形码
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
所以目前每个条形码(和文本)都是黑色的。例如,有没有一种方法可以传入 Color
对象来为条形码和文本着色?我尝试了这个 hacky 解决方案来获取当前像素颜色,检查它是否为白色,如果不是,则将其着色为指定的字体颜色。
for (int x = 0; x < barCodeBitmap.Width; x++)
{
for (int y = 0; y < barCodeBitmap.Height; y++)
{
Color currentColor = barCodeBitmap.GetPixel(x, y);
bool isWhite = currentColor == Color.White;
if (!isWhite) // this pixel should get a new color
{
barCodeBitmap.SetPixel(x, y, fontColor); // set a new color
}
}
}
不幸的是每个像素都被着色了..
要为整个代码(包括文本)着色,您可以使用以下代码片段:
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
},
Renderer = new BitmapRenderer
{
Foreground = Color.Red
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
如果您想要条形码和文本的不同颜色,您必须编写自己的渲染器实现并使用它而不是 BitmapRenderer。
您可以查看 BitmapRenderer 的源代码并将其用作您自己实现的模板:
https://github.com/micjahn/ZXing.Net/blob/master/Source/lib/renderer/BitmapRenderer.cs
例如添加一个新的属性 "TextColor"并在行
中使用它
var brush = new SolidBrush(Foreground);
改为
var brush = new SolidBrush(TextColor);
我正在使用 ZXing.NET 和此代码
生成条形码BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
所以目前每个条形码(和文本)都是黑色的。例如,有没有一种方法可以传入 Color
对象来为条形码和文本着色?我尝试了这个 hacky 解决方案来获取当前像素颜色,检查它是否为白色,如果不是,则将其着色为指定的字体颜色。
for (int x = 0; x < barCodeBitmap.Width; x++)
{
for (int y = 0; y < barCodeBitmap.Height; y++)
{
Color currentColor = barCodeBitmap.GetPixel(x, y);
bool isWhite = currentColor == Color.White;
if (!isWhite) // this pixel should get a new color
{
barCodeBitmap.SetPixel(x, y, fontColor); // set a new color
}
}
}
不幸的是每个像素都被着色了..
要为整个代码(包括文本)着色,您可以使用以下代码片段:
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
},
Renderer = new BitmapRenderer
{
Foreground = Color.Red
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
如果您想要条形码和文本的不同颜色,您必须编写自己的渲染器实现并使用它而不是 BitmapRenderer。 您可以查看 BitmapRenderer 的源代码并将其用作您自己实现的模板:
https://github.com/micjahn/ZXing.Net/blob/master/Source/lib/renderer/BitmapRenderer.cs
例如添加一个新的属性 "TextColor"并在行
中使用它var brush = new SolidBrush(Foreground);
改为
var brush = new SolidBrush(TextColor);