Tagliatti / NetBarcode

Barcode generation library written in C# and .NET Standard 2
MIT License
337 stars 68 forks source link

DrawLines method from ImageSharp does not render the barcode lines correctly #34

Open xtomino opened 2 years ago

xtomino commented 2 years ago

Hi @Tagliatti, first of all, thank you for your library!

I have been using the library for some time, namely for Code128C. I encountered a problem with versions 1.5+, which I already wrote about (Issue #29).

var barcode = new Barcode("660004005000080000221020220529113509", NetBarcode.Type.Code128C, false, 466, 40);
barcode.SaveImageFile(@"C:\Temp\barcode.png", ImageFormat.Png);

Result for version 1.4.5 barcode145 Result for version 1.6.0 barcode16original

In the latest version barcode lines are rendered as thicker and when I use barcode.GetBase64Image(); the barcode is really corrupted. barcode-B64

I tried to figure out the cause of the problem and found that the problem is in this part of the code:

imageContext.DrawLines(drawingOptions, pen,
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth, 0),
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth, _height - labelHeight)
);

The problem is with ImageSharp method DrawLines. This method will not draw a line in the form of a solid rectangle if the pen width is equal to or greater than 2 :-(

I suggest using the method FillPolygon, and the corresponding code would look like this:

imageContext.FillPolygon(drawingOptions, _foregroundColor,
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth, 0),
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth + iBarWidth / iBarWidthModifier, 0),
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth + iBarWidth / iBarWidthModifier, _height - labelHeight),
    new PointF(pos * iBarWidth + shiftAdjustment + halfBarWidth, _height - labelHeight));

The variable pen is no longer needed. And result for modified version 1.6.0 is the same as the one generated by the library version 1.4.5! barcode16modified

What do you think? Wouldn't it work better this way?

Tagliatti commented 2 years ago

Hello @xtomino , I did a little test on your solution, I'll just test a little more calmly. Thanks for the help.