Building UWP Barcode Reader with C++/WinRT and JavaScript

This article shows how to use Dynamsoft C++ barcode reader SDK to create a Window runtime component, as well as how to use the WinRT component and JavaScript to build a UWP app on Windows 10.

Prerequisites

Building WinRT Component with C++ DLLs

Create a new Windows Runtime Component project by using the C++ template.

windows runtime component

Open the properties of the Windows Runtime Component project to add the path of header files and library files, as well as add the input dependency.

dynamsoft barcode reader header files

dynamsoft barcode reader lib directory

dynamsoft barcode reader libs

According to the dependent libraries, change the build platform from Any CPU to x86 or x64.

anycpu x86 x64

Rename default class to BarcodeReader and add a new method DecodeFileStream().

BarcodeReader.h:

#pragma once
#include "DynamsoftBarcodeReader.h"

#include <wrl.h>
#include <robuffer.h>

using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Microsoft::WRL;
using namespace Platform;

namespace Dynamsoft
{
    public ref class BarcodeReader sealed
    {
    public:
        BarcodeReader();
		Array<String^>^ DecodeFileStream(IBuffer^ pixelBuffer);
    };
}

BarcodeReader.cpp:

#include "pch.h"
#include "BarcodeReader.h"

using namespace Dynamsoft;
using namespace Platform;

BarcodeReader::BarcodeReader()
{
}

byte* GetPointerToPixelData(IBuffer^ pixelBuffer, unsigned int *length)
{
	if (length != nullptr)
	{
		*length = pixelBuffer->Length;
	}
	// Query the IBufferByteAccess interface.
	ComPtr<IBufferByteAccess> bufferByteAccess;
	reinterpret_cast<IInspectable*>(pixelBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess));

	// Retrieve the buffer data.
	byte* pixels = nullptr;
	bufferByteAccess->Buffer(&pixels);
	return pixels;
}

Array<String^>^ BarcodeReader::DecodeFileStream(IBuffer ^ pixelBuffer)
{
	CBarcodeReader reader;
	reader.InitLicense("t0068NQAAACqUjZa21C+W7fRdPkf2FRFRr+QpfVC2tDsl/8t25TzYCNxl5s0OkuwFgEMGNfN95Z0HYQ55ROi1px9JqVAP7/c=");
	unsigned int length = 0;
	byte* buffer = GetPointerToPixelData(pixelBuffer, &length);
	int ret = reader.DecodeFileInMemory(buffer, length, "");
	STextResultArray *paryResult = NULL;
	reader.GetAllTextResults(&paryResult);

	Array<String^>^ results = ref new Array<String^>(paryResult->nResultsCount);
	for (int i = 0; i < paryResult->nResultsCount; ++i) {
		std::string s_str = std::string(paryResult->ppResults[i]->pszBarcodeText);
		std::wstring wid_str = std::wstring(s_str.begin(), s_str.end());
		const wchar_t* w_char = wid_str.c_str();
		results->set(i, ref new String(w_char));
	}

	return results;
}

Build the project to generate Dynamsoft.winmd and Dynamsoft.dll.

Building a Simple UWP Barcode Reader in JavaScript

Create a new UWP project by using the JavaScript template.

UWP barcode

Add the created Windows Runtime Component project as a reference.

project reference

Add a button and a div to index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>UWPBarcode</title>
    <link href="css/default.css" rel="stylesheet" />
</head>
<body>
    <h1>Dynamsoft Barcode Reader</h1>
    <button type="button" id="fileinput">Load an image</button>
    <div id="results"></div>
    <script src="js/main.js"></script>
</body>
</html>

Use file picker to load an image from local disk, and call the native API to decode barcodes in main.js:

var reader = new Dynamsoft.BarcodeReader();
function readBarcode() {
    var picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
    picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
    picker.fileTypeFilter.append(".jpg");
    picker.fileTypeFilter.append(".jpeg");
    picker.fileTypeFilter.append(".png");

    picker.pickSingleFileAsync().then(function(file) {
        if (file != null) {
            Windows.Storage.FileIO.readBufferAsync(file).then(function (buffer) {
                let result = reader.decodeFileStream(buffer);
                document.getElementById('results').innerHTML = JSON.stringify(result);
            }
            );
        }
        else {
            document.getElementById('results').innerHTML = "Operation cancelled.";
        }
    });
}

document.getElementById('fileinput').addEventListener('click', readBarcode, false);

Add dependent native DLLs to the project and set “Copy always” as the build action.

dll copy

Build and run the app.

UWP winrt barcode reader

References

Source Code

https://github.com/yushulx/winrt-javascript-uwp