Dynamsoft недавно выпустила SDK Barcode Reader v5.0 для Windows. Вы можете думать об этом как о совершенно новом продукте, потому что переопределено большое количество API и структур данных. Если вы загрузили DBR v5.0 и попытались создать с его помощью надстройку штрих-кода Node.js, вам придется потратить некоторое время на изменение примера кода, написанного для DBR v4.x. В этой статье я расскажу о разнице между DBR v4.x и DBR v5.0, а также о том, как обновить текущий код, чтобы он соответствовал новым интерфейсам.
Предпосылки
- ДБР v5.0
- Узел v5.5.0
- Нпм 3.3.12
- Узел-гип v3.5.0
Изменения DBR v5.0
Несколько файлов заголовков, использовавшихся в версии 4.3, теперь объединены в файл заголовка DynamsoftBarcodeReader.h. Теперь более лаконично:
Все форматы штрих-кода были переименованы, поэтому вам нужно изменить код:
Концы интерфейсов, которые использовались в DBR v4.3, добавляются с «Ex».
До
- DBR_API int DBR_DecodeFile(const char* pFileName,
константа pReaderOptions pOption,
pBarcodeResultArray *ppResults);
- DBR_API int DBR_DecodeBuffer(unsigned char* pDIBBuffer,
интервал iBufferSize,
константа pReaderOptions pOptions,
pBarcodeResultArray *ppResults
);
- DBR_API int DBR_DecodeStream(unsigned char* pFileStream,int iFileSize,
константа pReaderOptions pOptions,
pBarcodeResultArray* ppResults);
После
- DBR_API int DBR_DecodeFileEx(void* hBarcode, const char* pFileName, SBarcodeResultArray **ppResults);
- DBR_API int DBR_DecodeBufferEx(void* hBarcode, unsigned char* pBuffer, int iWidth, int iHeight, int iStride, формат ImagePixelFormat, SBarcodeResultArray **ppResults);
- DBR_API int DBR_DecodeStreamEx(void* hBarcode, unsigned char* pFileStream, int iFileSize, SBarcodeResultArray **ppResults);
Структуры данных, относящиеся к штрих-коду, также переименованы.
До
typedef
struct
tagBarcodeResult
{
__int64
llFormat;
char* pBarcodeData;
int
iBarcodeDataLength;
int
iLeft;
int
iTop;
int
iWidth;
int
iHeight;
int
iX1;
int
iY1;
int
iX2;
int
iY2;
int
iX3;
int
iY3;
int
iX4;
int
iY4;
int
iPageNum;
} BarcodeResult, *pBarcodeResult;
typedef
struct
tagBarcodeResultArray
{
int
iBarcodeCount;
pBarcodeResult *ppBarcodes;
} BarcodeResultArray, *pBarcodeResultArray;
После
typedef
struct
tagSBarcodeResult
{
BarcodeFormat emBarcodeFormat;
char* pBarcodeData;
int
iBarcodeDataLength;
int
iLeft;
int
iTop;
int
iWidth;
int
iHeight;
int
iX1;
int
iY1;
int
iX2;
int
iY2;
int
iX3;
int
iY3;
int
iX4;
int
iY4;
int
iPageNum;
wchar_t* pBarcodeText;
int
iAngle;
int
iModuleSize;
BOOL
bIsUnrecognized;
const
char* pBarcodeFormatString;
} SBarcodeResult;
typedef
struct
tagSBarcodeResultArray
{
int
iBarcodeCount;
SBarcodeResult **ppBarcodes;
} SBarcodeResultArray;
Обновление надстройки штрих-кода Node.js
Откройте binding.gyp и укажите путь к заголовку и библиотеке DBR v5.0. Поскольку DBR v5.0 поддерживает только Windows, вам не нужно добавлять настройки для macOS и Linux.
{
"targets": [
{
'target_name': "dbr",
'sources': [ "dbr.cc" ],
'conditions': [
['OS=="win"', {
'defines': [
'WINDOWS_DBR',
],
'include_dirs': [
"E:\Program Files (x86)\Dynamsoft\Barcode Reader 5.0\Components\C_C++\Include"
],
'libraries': [
"-lE:\Program Files (x86)\Dynamsoft\Barcode Reader 5.0\Components\C_C++\Lib\DBRx64.lib"
],
'copies': [
{
'destination': 'build/Release/',
'files': [
'E:\Program Files (x86)\Dynamsoft\Barcode Reader 5.0\Components\C_C++\Redist\DynamsoftBarcodeReaderx64.dll'
]
}]
}]
]
}
]
}
Откройте файл dbr.cc. При использовании DBR v4.x функцию InitLicense вызывать не нужно. С DBR v5.0 вам нужно использовать его для создания обработчика DBR.
void
InitLicense(const
FunctionCallbackInfo<Value>& args) {
String::Utf8Value license(args[0]->ToString());
char
*pszLicense = *license;
hBarcode = DBR_CreateInstance();
DBR_InitLicenseEx(hBarcode, pszLicense);
}
Измените код обнаружения новыми методами:
static
void
DetectionWorking(uv_work_t *req)
{
if
(!hBarcode)
{
printf("Barcode reader handler not initialized.\n");
return;
}
// get the reference to BarcodeWorker
BarcodeWorker *worker = static_cast<BarcodeWorker *>(req->data);
// initialize Dynamsoft Barcode Reader
int
iMaxCount = 0x7FFFFFFF;
SBarcodeResultArray *pResults = NULL;
DBR_SetBarcodeFormats(hBarcode, worker->iFormat);
DBR_SetMaxBarcodesNumPerPage(hBarcode, iMaxCount);
// decode barcode image
int
ret = 0;
switch(worker->bufferType)
{
case
FILE_STREAM:
{
if
(worker->buffer)
ret = DBR_DecodeStreamEx(hBarcode, worker->buffer, worker->size, &pResults);
}
break;
case
YUYV_BUFFER:
{
if
(worker->buffer)
{
int
dibsize = 0;
int
width = worker->width, height = worker->height;
int
size = width * height;
int
index = 0;
unsigned char* data = new
unsigned char[size];
// get Y from YUYV
for
(int
i = 0; i < size; i++)
{
data[i] = worker->buffer[index];
index += 2;
}
// gray conversion
// ConvertCameraGrayDataToDIBBuffer(data, size, width, height, &pdibdata, &dibsize);
// read barcode
ret = DBR_DecodeBufferEx(hBarcode, data, width, height, width, IPF_GrayScaled, &pResults);
// release memory
delete
[]data, data=NULL;
}
}
break;
default:
{
ret = DBR_DecodeFileEx(hBarcode, worker->filename, &pResults);
}
}
if
(ret)
printf("Detection error code: %d\n", ret);
// save results to BarcodeWorker
worker->errorCode = ret;
worker->pResults = pResults;
}
Соберите аддон:
node-gyp configure
node-gyp build
В dbr.js сначала вызовите initLicense, а затем вызовите другие интерфейсы обнаружения штрих-кода.
rl.question("Please input a barcode image path: ", function(answer) {
dbr.initLicense("");
decodeFileStreamAsync(answer);
decodeFileAsync(answer);
// decodeYUYVAsync(answer, 640, 480);
rl.close();
});
Пришло время использовать Dynamsoft Barcode Reader v5.0 для создания надстройки штрих-кода Node.js.