О продукте
ОтзывыFirst of all, let me compliment you on your Barcode.NET Library. We evaluated a number of products to use in our application, and yours was our favorite. Dan Konigsberg |
VintaSoftBarcode.NET SDK - FAQОбщие вопросы:
Распространение:
Программирование:
Для каких целей я могу использовать библиотеку VintaSoftBarcode.NET?Данная библиотека может использоваться для распознавания и создания одномерных, почтовых и двухмерных штрих-кодов в изображениях и PDF файлах.
Что включает в себя библиотека?Библиотека включает в себя:
В каких языках программирования я могу использовать библиотеку VintaSoftBarcode.NET?Лицензия разработчика и лицензия для компании позволяют использовать компонент в:
Лицензия для сервера позволяет использовать компонент в:
Какие ограничения имеет незарегистрированная версия библиотеки?Незарегистрированная версия библиотеки имеет следующие ограничения:
Я не нашел ответа на свой вопрос. Что мне делать?Информация по большинству вопросов может быть найдена в документации или в этом FAQ. Если Вы не нашли ответа на свой вопрос, тогда напишите письмо в службу технической поддержки.
Какие файлы мне нужно включать в дистрибутив моей программы?Вам нужно включить в дистрибутив Вашей программы только один файл: Vintasoft.Barcode.dll. При установке Вашей программы этот файл должен быть помещен в каталог на который была ссылка при компиляции программы.
Могу ли я распространять файл Vintasoft.Barcode.dll вместе с моим приложением без какой либо дополнительной оплаты?Да, Вы можете распространять файл Vintasoft.Barcode.dll вместе со своим приложением. Вы платите только за первоначальную регистрацию.
Как достичь максимальной скорости сканирования штрих-кодов?Здесь приведено несколько советов с помощю которых можно увеличить скорость чтения штрих-кодов:
Как мне получить стабильную систему генерации и распознавания штрих-кодов?Для настройки системы пользуйтесь свойством IBarcodeInfo.ReadingQuality.
Есть ли рекомендации по генерации одномерных штрих-кодов для дальнейшего успешного их распознавания?Наиболее устойчивы к повреждениям и искажениям, штрих-коды типа Code 39 и Code 128 (с контрольной суммой!).
Если штрих-код не имеет обязательной контрольной суммы (Code 39, Interleaved 2of5, Standard 2of5) используйте опциональную
контрольную сумму, что позволит избежать ошибок при чтении штрих-кодов из изображений плохого качества.
Есть ли рекомендации по генерации двухмерных штрих-кодов для дальнейшего успешного их распознавания?Наиболее устойчив к повреждениям и искажениям штрих-код типа Data Matrix. Наиболее компактыми штрих-кодами являются Data Matrix и Aztec. Далее следует Qr Code, затем PDF417.
Библиотека поддерживает мультипоточность?Да. Начиная с версии 5.0 основной алгоритм разбивается на N потоков.
Как распознать штрих-коды плохого качества в цветном(сером) изображении, если не удается подобрать threshold, а автоматическое определение threshold не помогает?Существуют два варианта:
[VB.NET]
Private Shared Sub ScanWithIterations(ByVal fileName As String, ByVal barcodes As BarcodeType, _
ByVal expectedBarcodes As Integer, ByVal iterationCount As Integer, ByVal minThreshold As Integer, ByVal maxThreshold As Integer)
Dim barcodeImage As Image = Image.FromFile(fileName)
Dim reader As New BarcodeReader()
reader.Settings.ScanBarcodeTypes = barcodes
reader.Settings.ExpectedBarcodes = expectedBarcodes
reader.Settings.ThresholdIterations = iterationCount
reader.Settings.Threshold1D = minThreshold
reader.Settings.Threshold2D = maxThreshold
' read barcodes
Dim barcodesInfo As IBarcodeInfo() = reader.readBarcodes(barcodeImage)
If barcodesInfo.Length = 0 Then
Console.WriteLine("No barcodes found.")
Else
For i As Integer = 0 To barcodesInfo.Length - 1
Dim inf As IBarcodeInfo = barcodesInfo(i)
Console.WriteLine(String.Format("[{0}] {1} (Threshold: {2})", inf.BarcodeType, inf.Value, inf.Threshold))
Next
End If
barcodeImage.Dispose()
End Sub
Private Shared Sub TestScanWithIterationsCode128orDataMatrix(ByVal fileName As String)
' find one Code 128 or DataMatrix barcode from 400 to 600 threshold (10 iterations)
ScanWithIterations(fileName, BarcodeType.Code128 Or BarcodeType.DataMatrix, 1, 10, 400, 600)
End Sub
[C#]
static void ScanWithIterations(string fileName, BarcodeType barcodes, int expectedBarcodes,
int iterationCount, int minThreshold, int maxThreshold)
{
Image barcodeImage = Image.FromFile(fileName);
BarcodeReader reader = new BarcodeReader();
reader.Settings.ScanBarcodeTypes = barcodes;
reader.Settings.ExpectedBarcodes = expectedBarcodes;
reader.Settings.ThresholdIterations = iterationCount;
reader.Settings.Threshold1D = minThreshold;
reader.Settings.Threshold2D = maxThreshold;
// read barcodes
IBarcodeInfo[] barcodesInfo = reader.ReadBarcodes(barcodeImage);
if (barcodesInfo.Length == 0)
{
Console.WriteLine("No barcodes found.");
}
else
{
for (int i = 0; i < barcodesInfo.Length; i++)
{
IBarcodeInfo inf = barcodesInfo[i];
Console.WriteLine(string.Format("[{0}] {1} (Threshold: {2})", inf.BarcodeType, inf.Value, inf.Threshold));
}
}
barcodeImage.Dispose();
}
static void TestScanWithIterationsCode128orDataMatrix(string fileName)
{
// find one Code 128 or DataMatrix barcode from 400 to 600 threshold (10 iterations)
ScanWithIterations(fileName, BarcodeType.Code128 | BarcodeType.DataMatrix, 1, 10, 400, 600);
}
Могу ли я считать штрих-коды из многостраничного файла TIFF?Да, вот пример:
[VB.NET]
Private Shared Sub ReadBarcodesFromMiltipageTiffFile(ByVal fileName As String, ByVal barcodes As BarcodeType)
' open tiff image
Dim tiffImage As Image = Image.FromFile(fileName)
Dim index As Guid = tiffImage.FrameDimensionsList(0)
Dim dimension As New FrameDimension(index)
Dim pageCount As Integer = tiffImage.GetFrameCount(dimension)
' create reader
Dim reader As New BarcodeReader()
reader.Settings.ScanBarcodeTypes = barcodes
' read barcodes from all pages
For i As Integer = 0 To pageCount - 1
' selects a page
tiffImage.SelectActiveFrame(dimension, i)
' read barcodes from page i
Dim barcodesInfo As IBarcodeInfo() = reader.readBarcodes(tiffImage)
' write information
Console.WriteLine(String.Format("Page {0}: ", i))
If barcodesInfo.Length = 0 Then
Console.WriteLine("No barcodes found.")
Else
For j As Integer = 0 To barcodesInfo.Length - 1
Console.WriteLine(String.Format("[{0}] {1}", barcodesInfo(j).BarcodeType, barcodesInfo(j).Value))
Next
End If
Next
' free resources
tiffImage.Dispose()
End Sub
[C#]
static void ReadBarcodesFromMiltipageTiffFile(string fileName, BarcodeType barcodes)
{
// open tiff image
Image tiffImage = Image.FromFile(fileName);
Guid index = tiffImage.FrameDimensionsList[0];
FrameDimension dimension = new FrameDimension(index);
int pageCount = tiffImage.GetFrameCount(dimension);
// create reader
BarcodeReader reader = new BarcodeReader();
reader.Settings.ScanBarcodeTypes = barcodes;
// read barcodes from all pages
for (int i = 0; i < pageCount; i++)
{
// selects a page
tiffImage.SelectActiveFrame(dimension, i);
// read barcodes from page i
IBarcodeInfo[] barcodesInfo = reader.ReadBarcodes(tiffImage);
// write information
Console.WriteLine(string.Format("Page {0}: ", i));
if (barcodesInfo.Length == 0)
{
Console.WriteLine("No barcodes found.");
}
else
{
for (int j = 0; j < barcodesInfo.Length; j++)
Console.WriteLine(string.Format("[{0}] {1}", barcodesInfo[j].BarcodeType, barcodesInfo[j].Value));
}
}
// free resources
tiffImage.Dispose();
}
Могу ли я считать штрих-коды из PDF документа?Да, вот пример:
[VB.NET]
Private Shared Sub ReadBarcodesFromPdfDocument(ByVal fileName As String, ByVal barcodes As BarcodeType)
' open PDF document
Dim pdfImageViewer As New PdfImageViewer(fileName)
' create reader
Dim reader As New BarcodeReader()
reader.Settings.ScanBarcodeTypes = barcodes
' read barcodes from all pages
For i As Integer = 0 To pdfImageViewer.PageCount - 1
' get all images names from page i
Dim imageNames As String() = pdfImageViewer.GetImageNames(i)
' foreach images in page i
For k As Integer = 0 To imageNames.Length - 1
Console.WriteLine(String.Format("Page {0}, image {1}: ", i, imageNames(k)))
Dim barcodeImage As Image
' get image with name imageNames[k]
Try
barcodeImage = pdfImageViewer.GetImage(i, imageNames(k))
Catch e As Exception
' not supported image format
Console.WriteLine(e.Message)
Continue For
End Try
' read barcodes
Dim barcodesInfo As IBarcodeInfo() = reader.readBarcodes(barcodeImage)
' write information
If barcodesInfo.Length = 0 Then
Console.WriteLine("No barcodes found.")
Else
For j As Integer = 0 To barcodesInfo.Length - 1
Console.WriteLine(String.Format("[{0}] {1}", barcodesInfo(j).BarcodeType, barcodesInfo(j).Value))
Next
End If
Next
Next
' free resources
pdfImageViewer.Dispose()
End Sub
[C#]
static void ReadBarcodesFromPdfDocument(string fileName, BarcodeType barcodes)
{
// open PDF document
PdfImageViewer pdfImageViewer = new PdfImageViewer(fileName);
// create reader
BarcodeReader reader = new BarcodeReader();
reader.Settings.ScanBarcodeTypes = barcodes;
// read barcodes from all pages
for (int i = 0; i < pdfImageViewer.PageCount; i++)
{
// get all images names from page i
string[] imageNames = pdfImageViewer.GetImageNames(i);
// foreach images in page i
for (int k = 0; k < imageNames.Length; k++)
{
Console.WriteLine(string.Format("Page {0}, image {1}: ", i, imageNames[k]));
Image barcodeImage;
// get image with name imageNames[k]
try
{
barcodeImage = pdfImageViewer.GetImage(i, imageNames[k]);
}
catch(Exception e)
{
// not supported image format
Console.WriteLine(e.Message);
continue;
}
// read barcodes
IBarcodeInfo[] barcodesInfo = reader.ReadBarcodes(barcodeImage);
// write information
if (barcodesInfo.Length == 0)
{
Console.WriteLine("No barcodes found.");
}
else
{
for (int j = 0; j < barcodesInfo.Length; j++)
Console.WriteLine(string.Format("[{0}] {1}", barcodesInfo[j].BarcodeType, barcodesInfo[j].Value));
}
}
}
// free resources
pdfImageViewer.Dispose();
}
Как я могу поместить штрихкод в PDF документ в векторной форме?Вот пример:
[VB.NET]
' Important: You need Vintasoft.Barcode.dll, Vintasoft.Imaging.dll, Vintasoft.Pdf.dll assemblies to run this code.
Private Shared Sub MarkPDF(ByVal pdfFilename As String)
' create barcodeWriter
Dim barcodeWriter As New BarcodeWriter()
' using DataMatrix 2D barcode
barcodeWriter.Settings.Barcode = BarcodeType.Code128
' barcode padding
Dim padding As Single = 5
' open PDF document
Dim document As New PdfDocument(pdfFilename)
' foreach pages
For i As Integer = 0 To document.Pages.Count - 1
Dim page As PdfPage = document.Pages(i)
' barcode value - page number
barcodeWriter.Settings.Value = (i + 1).ToString()
' write barcode graphics path
Dim barcodePath As GraphicsPath = barcodeWriter.GetBarcodeAsGraphicsPath()
' translate barcode to right-bottom page corner
Using m As New Matrix()
Dim barcodeWidth As Single = barcodePath.GetBounds().Width
m.Translate(page.MediaBox.Right - barcodeWidth - padding, padding)
barcodePath.Transform(m)
End Using
' fill barcode path
Using g As PdfGraphics = page.GetGraphics()
Dim brush As New PdfBrush(Color.Black)
g.FillPath(brush, barcodePath)
End Using
barcodePath.Dispose()
Next
' saving document
Dim resultFileName As String = Path.GetFileNameWithoutExtension(pdfFilename) & "_marked.pdf"
document.Save(Path.Combine(Path.GetDirectoryName(pdfFilename), resultFileName))
' free resources
document.Dispose()
End Sub
[C#]
// Important: You need Vintasoft.Barcode.dll, Vintasoft.Imaging.dll, Vintasoft.Pdf.dll assemblies to run this code.
static void MarkPDF(string pdfFilename)
{
// create barcodeWriter
BarcodeWriter barcodeWriter = new BarcodeWriter();
// using DataMatrix 2D barcode
barcodeWriter.Settings.Barcode = BarcodeType.DataMatrix;
// barcode padding
float padding = 5;
// open PDF document
PdfDocument document = new PdfDocument(pdfFilename);
// foreach pages
for (int i = 0; i < document.Pages.Count; i++)
{
PdfPage page = document.Pages[i];
// barcode value - page number
barcodeWriter.Settings.Value = (i + 1).ToString();
// write barcode graphics path
GraphicsPath barcodePath = barcodeWriter.GetBarcodeAsGraphicsPath();
// translate barcode to right-bottom page corner
using (Matrix m = new Matrix())
{
float barcodeWidth = barcodePath.GetBounds().Width;
m.Translate(page.MediaBox.Right - barcodeWidth - padding, padding);
barcodePath.Transform(m);
}
// fill barcode path
using (PdfGraphics g = page.GetGraphics())
{
PdfBrush brush = new PdfBrush(Color.Black);
g.FillPath(brush, barcodePath);
}
barcodePath.Dispose();
}
// saving document
string resultFileName = Path.GetFileNameWithoutExtension(pdfFilename) + "_marked.pdf";
document.Save(Path.Combine(Path.GetDirectoryName(pdfFilename), resultFileName));
// free resources
document.Dispose();
}
Как я могу сделать собственную контрольную сумму в штрих-коде и прочитать такой штрих-код?Вы должны использовать свойство ReaderSettings.VerifyBarcodeMethod для проверки правильности штрих-кода(его контрольной суммы). Вот пример кода который иллюстрирует как создать и распознать Code 39 штрих-код с контрольной суммой по модулю 1000:
[VB.NET]
' Generate checksum at base 1000.
Private Shared Function GenerateChecksum(ByVal value As String) As String
Dim checkSum As Integer = 0
For i As Integer = 0 To value.Length - 1
checkSum += CByte(AscW(value(i))) * i
checkSum = checkSum Mod 1000
Next
'result - [000..999]
Return checkSum.ToString().PadLeft(3, "0"c)
End Function
' Testing Checksum in barcode value.
Private Shared Function TestChecksum(ByVal barcodeValue As String) As Boolean
Dim value As String = barcodeValue.Substring(0, barcodeValue.Length - 3)
Dim readChecksum As String = barcodeValue.Substring(barcodeValue.Length - 3)
Return readChecksum = GenerateChecksum(value)
End Function
' Verify barcode method.
Private Shared Sub VerifyBarcodeMethod(ByVal reader As BarcodeReader, ByVal barcodeInfo As IBarcodeInfo)
If TestChecksum(barcodeInfo.Value) Then
barcodeInfo.Confidence = 100
Else
barcodeInfo.Confidence = 0
End If
End Sub
Private Shared Sub TestCode39Barcode(ByVal value As String)
' create writer
Dim writer As New BarcodeWriter()
writer.Settings.Barcode = BarcodeType.Code39
' create reader
Dim reader As New BarcodeReader()
reader.Settings.ScanBarcodeTypes = BarcodeType.Code39
reader.Settings.MinConfidence = 100
reader.Settings.AutomaticRecognition = True
reader.Settings.ExpectedBarcodes = 1
' write barcode without checksum
writer.Settings.Value = value
Dim barcodeNoChecksumImage As Image = writer.GetBarcodeAsBitmap()
' write barcode with checksum
writer.Settings.Value = value & GenerateChecksum(value)
Dim barcodeWithMyChecksumImage As Image = writer.GetBarcodeAsBitmap()
'set VerifyBarcodeMethod
reader.Settings.VerifyBarcodeMethod = AddressOf VerifyBarcodeMethod
Dim infos As IBarcodeInfo()
'read barcodes from barcode image without checksum
'no barcodes found
infos = reader.readBarcodes(barcodeNoChecksumImage)
Console.WriteLine("Scan (NoChecksum):")
For i As Integer = 0 To infos.Length - 1
Console.WriteLine(infos(i).Value)
Next
'read barcodes from barcode image with checksum
'found one barcode
infos = reader.readBarcodes(barcodeWithMyChecksumImage)
Console.WriteLine("Scan (MyChecksum):")
For i As Integer = 0 To infos.Length - 1
Console.WriteLine(infos(i).Value)
Next
End Sub
[C#]
// Generate checksum at base 1000.
static string GenerateChecksum(string value)
{
int checkSum = 0;
for (int i = 0; i < value.Length; i++)
{
checkSum += ((byte)value[i]) * i;
checkSum %= 1000;
}
//result - [000..999]
return checkSum.ToString().PadLeft(3, '0');
}
// Testing Checksum in barcode value.
static bool TestChecksum(string barcodeValue)
{
string value = barcodeValue.Substring(0, barcodeValue.Length - 3);
string readChecksum = barcodeValue.Substring(barcodeValue.Length - 3);
return readChecksum == GenerateChecksum(value);
}
// Verify barcode method.
static void VerifyBarcodeMethod(BarcodeReader reader, IBarcodeInfo barcodeInfo)
{
if (TestChecksum(barcodeInfo.Value))
barcodeInfo.Confidence = 100;
else
barcodeInfo.Confidence = 0;
}
static void TestCode39Barcode(string value)
{
// create writer
BarcodeWriter writer = new BarcodeWriter();
writer.Settings.Barcode = BarcodeType.Code39;
// create reader
BarcodeReader reader = new BarcodeReader();
reader.Settings.ScanBarcodeTypes = BarcodeType.Code39;
reader.Settings.MinConfidence = 100;
reader.Settings.AutomaticRecognition = true;
reader.Settings.ExpectedBarcodes = 1;
// write barcode without checksum
writer.Settings.Value = value;
Image barcodeNoChecksumImage = writer.GetBarcodeAsBitmap();
// write barcode with checksum
writer.Settings.Value = value + GenerateChecksum(value);
Image barcodeWithMyChecksumImage = writer.GetBarcodeAsBitmap();
//set VerifyBarcodeMethod
reader.Settings.VerifyBarcodeMethod = VerifyBarcodeMethod;
IBarcodeInfo[] infos;
//read barcodes from barcode image without checksum
//no barcodes found
infos = reader.ReadBarcodes(barcodeNoChecksumImage);
Console.WriteLine("Scan (NoChecksum):");
for (int i = 0; i < infos.Length; i++)
Console.WriteLine(infos[i].Value);
//read barcodes from barcode image with checksum
//found one barcode
infos = reader.ReadBarcodes(barcodeWithMyChecksumImage);
Console.WriteLine("Scan (MyChecksum):");
for (int i = 0; i < infos.Length; i++)
Console.WriteLine(infos[i].Value);
}
Как я могу нарисовать штрих-код с заданными размерами в нужном мне разрешении(DPI)?
[VB.NET]
Private Shared Function DrawBarcode(ByVal barcode As BarcodeType, ByVal value As String, ByVal resolution As Single, _
ByVal width As Single, ByVal height As Single, ByVal units As UnitOfMeasure) As Image
Dim writer As New BarcodeWriter()
writer.Settings.Barcode = barcode
writer.Settings.Value = value
writer.Settings.Resolution = resolution
writer.Settings.SetWidth(width, units)
writer.Settings.SetHeight(height, units)
Return writer.GetBarcodeAsBitmap()
End Function
Private Shared Sub TestDrawBarcode(ByVal fileName As String)
' Draw barcode 6x2 cm in 600 DPI
Dim barcodeImage As Image = DrawBarcode(BarcodeType.Code128, "TESTBARCODE", 600, 6, 2, UnitOfMeasure.Centimeters)
barcodeImage.Save(fileName)
barcodeImage.Dispose()
End Sub
[C#]
static Image DrawBarcode(BarcodeType barcode, string value, float resolution, float width, float height, UnitOfMeasure units)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Settings.Barcode = barcode;
writer.Settings.Value = value;
writer.Settings.Resolution = resolution;
writer.Settings.SetWidth(width, units);
writer.Settings.SetHeight(height, units);
return writer.GetBarcodeAsBitmap();
}
static void TestDrawBarcode(string fileName)
{
// Draw barcode 6x2 cm in 600 DPI
Image barcodeImage = DrawBarcode(BarcodeType.Code128, "TESTBARCODE", 600, 6, 2, UnitOfMeasure.Centimeters);
barcodeImage.Save(fileName);
barcodeImage.Dispose();
}
|