【问题标题】:Colorize barcode bitmap by Color按颜色着色条码位图
【发布时间】:2020-03-21 18:25:03
【问题描述】:

我正在使用 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
        }
    }
}

不幸的是,每个像素都被着色了..

【问题讨论】:

    标签: c# zxing zxing.net


    【解决方案1】:

    要为整个代码(包括文本)着色,您可以使用以下 sn-p:

    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);
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多