目录

detectBarcode (Recognizing Barcodes in an Image)

Module Overview

The detectBarcode module provides the capability of recognizing barcodes from an image. An image can be input through a local image path or byte array to recognize barcodes, QR codes, and multifunctional codes in the image. This is applicable to scenarios where barcode image information needs to be extracted from album images or other image data (such as camera preview streams).

To help you quickly get started, you are advised to refer to the official sample project.

Since: 4.1.0(11)

Modules to Import

import { detectBarcode } from '@kit.ScanKit';

InputImage

Information about the image to be recognized.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.1.0(11)

Name Type Read-Only Optional Description
uri string No No Image path, for example, file://media/Photo/x/xxx.jpg.

Example:

You can use PhotoViewPicker to obtain the image path.

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';


let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 1;
photoSelectOptions.isPhotoTakingSupported = false;
photoSelectOptions.isEditSupported = false;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(photoSelectOptions).then((data: photoAccessHelper.PhotoSelectResult) => {
  if (!data || (data.photoUris && data.photoUris.length === 0)) {
    hilog.error(0x0001, 'picker', 'Failed to get PhotoSelectResult by promise');
    return;
  }
  hilog.info(0x0001, 'picker', `Succeeded in getting PhotoSelectResult by promise.`);
}).catch((err: BusinessError) => {
  hilog.error(0x0001, 'picker', `Failed to get PhotoSelectResult by promise. Code: ${err.code}`);
});

decode

decode(inputImage: InputImage, options?: scanBarcode.ScanOptions): Promise<Array<scanBarcode.ScanResult>>

Calls the image-based barcode scanning API by setting parameters and obtains the scanning result. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
inputImage InputImage Yes Information about the image to be recognized.
options scanBarcode.ScanOptions No

Parameters for starting image-based barcode scanning.

Default value: Refer to the default value of ScanOptions.

Returns:

Type Description
Promise<Array<scanBarcode.ScanResult>> Promise used to return the result object array.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.

Example:

import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Define scanning parameters.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };
// Use PhotoViewPicker to open the gallery and select an image.
let photoOption = new photoAccessHelper.PhotoSelectOptions();
photoOption.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoOption.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(photoOption).then((data) => {
  // Define the barcode scanning parameter inputImage. The uri parameter indicates the path of the image selected by PhotoViewPicker.
  let inputImage: detectBarcode.InputImage = { uri: data.photoUris[0] };
  try {
    // Call the image recognition API.
    detectBarcode.decode(inputImage, options).then((data: Array<scanBarcode.ScanResult>) => {
      hilog.info(0x0001, '[Scan Sample]',
        `Succeeded in getting ScanResult by promise with options, result length: ${data.length}`);
    }).catch((err: BusinessError) => {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to get ScanResult by promise with options. Code: ${err.code}, message: ${err.message}`);
    });
  } catch (err) {
    hilog.error(0x0001, '[Scan Sample]',
      `Failed to detect Barcode. Code: ${err.code}, message: ${err.message}`);
  }
}).catch((err: BusinessError) => {
  hilog.error(0x0001, 'picker', `Failed to get PhotoSelectResult by promise. Code: ${err.code}.`);
});

decode

decode(inputImage: InputImage, options: scanBarcode.ScanOptions, callback: AsyncCallback<Array<scanBarcode.ScanResult>>): void

Calls the image-based barcode scanning API by setting parameters and obtains the scanning result. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
inputImage InputImage Yes Information about the image to be recognized.
options scanBarcode.ScanOptions Yes Parameters for starting image-based barcode scanning.
callback AsyncCallback<Array<scanBarcode.ScanResult>> Yes Callback function. If the barcode scanning is successful, err is undefined and data is the obtained scanning result Array<scanBarcode.ScanResult>. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.

Example:

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Define scanning parameters.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };
// Use PhotoViewPicker to open the gallery and select an image.
let photoOption = new photoAccessHelper.PhotoSelectOptions();
photoOption.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoOption.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(photoOption).then((data) => {
  // Define the barcode scanning parameter inputImage. The uri parameter indicates the path of the image selected by PhotoViewPicker.
  let inputImage: detectBarcode.InputImage = { uri: data.photoUris[0] };
  try {
    // Call the image recognition API.
    detectBarcode.decode(inputImage, options, (err: BusinessError, data: Array<scanBarcode.ScanResult>) => {
      if (err && err.code) {
        hilog.error(0x0001, '[Scan Sample]',
          `Failed to get ScanResult by callback with options. Code: ${err.code}, message: ${err.message}`);
        return;
      }
      hilog.info(0x0001, '[Scan Sample]',
        `Succeeded in getting ScanResult by callback with options, result length: ${data.length}`);
    });
  } catch (err) {
    hilog.error(0x0001, '[Scan Sample]',
      `Failed to detect Barcode. Code: ${err.code}, message: ${err.message}`);
  }
}).catch((err: BusinessError) => {
  hilog.error(0x0001, 'picker', `Failed to get PhotoSelectResult by promise. Code: ${err.code}`);
});

decode

decode(inputImage: InputImage, callback: AsyncCallback<Array<scanBarcode.ScanResult>>): void

Calls the image-based barcode scanning API and obtains the scanning result. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
inputImage InputImage Yes Information about the image to be recognized.
callback AsyncCallback<Array<scanBarcode.ScanResult>> Yes Callback function. If the barcode scanning is successful, err is undefined and data is the obtained scanning result Array<scanBarcode.ScanResult>. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.

Example:

import { scanBarcode, detectBarcode } from '@kit.ScanKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Use PhotoViewPicker to open the gallery and select an image.
let photoOption = new photoAccessHelper.PhotoSelectOptions();
photoOption.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoOption.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(photoOption).then((data) => {
  // Define the barcode scanning parameter inputImage. The uri parameter indicates the path of the image selected by PhotoViewPicker.
  let inputImage: detectBarcode.InputImage = { uri: data.photoUris[0] };
  try {
    // Call the image recognition API.
    detectBarcode.decode(inputImage, (err: BusinessError, data: Array<scanBarcode.ScanResult>) => {
      if (err && err.code) {
        hilog.error(0x0001, '[Scan Sample]',
          `Failed to get ScanResult by callback. Code: ${err.code}, message: ${err.message}`);
        return;
      }
      hilog.info(0x0001, '[Scan Sample]',
        `Succeeded in getting ScanResult by callback, result length: ${data.length}`);
    });
  } catch (err) {
    hilog.error(0x0001, '[Scan Sample]',
      `Failed to detect Barcode. Code: ${err.code}, message: ${err.message}`);
  }
}).catch((err: BusinessError) => {
  hilog.error(0x0001, 'picker', `Failed to get PhotoSelectResult by promise. Code: ${err.code}`);
});

ByteImage

Image data to be recognized.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 5.0.0(12)

Name Type Read-Only Optional Description
byteBuffer ArrayBuffer No No Image data. which is a byte array for storing image data.
width number No No Image width, in pixels.
height number No No Image height, in pixels.
format ImageFormat No No Image data type (byteBuffer). Currently, only the NV21 pixel format is supported.

Example:

The buffer in the example can be obtained from the camera preview stream data. For details, please refer to Dual-Channel Preview.

import { detectBarcode } from '@kit.ScanKit';

// Buffer, height, and width data of the image, which can be obtained from the camera preview stream data. This example assumes that the width and height obtained are 1920 × 1080.
let byteImg: detectBarcode.ByteImage = {
  byteBuffer: buffer,
  width: 1920,
  height: 1080,
  format: detectBarcode.ImageFormat.NV21
};

ImageFormat

Enumerates the image data types.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 5.0.0(12)

Name Value Description
NV21 0 The pixel format of the image is NV21.

DetectResult

Recognition result. which is returned by the decodeImage API, including the recognition result and the recommended camera zoom level.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 5.0.0(12)

Name Type Read-Only Optional Description
scanResults Array<scanBarcode.ScanResult> No No Scanning result.
zoomValue number No No

Expected zoom ratio. When the value is greater than 1, you can use setZoomRatio to zoom in on the image.

NOTE

1. Use the Camera Kit getZoomRatio API to obtain the current zoom ratio of the camera.

2. Use the Camera Kit setZoomRatio API to set targetRatio. The target value is zoomRatio multiplied by zoomValue.

decodeImage

decodeImage(image: ByteImage, options?: scanBarcode.ScanOptions): Promise<DetectResult>

Calls the capability of image data barcode scanning by setting parameters to return the scanning result. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 5.0.0(12)

Parameters:

Parameter Type Mandatory Description
image ByteImage Yes Image data to be recognized.
options scanBarcode.ScanOptions No

Parameters for scanning barcodes from image data.

Default value: Refer to the default value of ScanOptions.

Returns:

Type Description
Promise<DetectResult> Promise used to return the barcode scanning result object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.

Example:

The buffer in the example can be obtained from the camera preview stream data. For details, please refer to Dual-Channel Preview.

import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Buffer, height, and width data of the image, which can be obtained from the camera preview stream data. This example assumes that the width and height obtained are 1920 × 1080.
let byteImg: detectBarcode.ByteImage = {
  byteBuffer: buffer,
  width: 1920,
  height: 1080,
  format: detectBarcode.ImageFormat.NV21
};
let options: scanBarcode.ScanOptions = {
  scanTypes: [scanCore.ScanType.ALL],
  enableMultiMode: true,
  enableAlbum: false
};
try {
  detectBarcode.decodeImage(byteImg, options).then((data: detectBarcode.DetectResult) => {
    hilog.info(0x0001, '[Scan Sample]',
      `Succeeded in getting DetectResult by promise with options, result length: ${data.scanResults.length}, zoomValue: ${data.zoomValue}`);
  }).catch((err: BusinessError) => {
    hilog.error(0x0001, '[Scan Sample]',
      `Failed to get DetectResult by promise with options. Code: ${err.code}, message: ${err.message}`);
  });
} catch (err) {
  hilog.error(0x0001, '[Scan Sample]', `Failed to decode Image. Code: ${err.code}, message: ${err.message}`);
}