目录

How Do I Set the Background Color of a Barcode Image to Transparent?

Problem

The current barcode image generation capability itself does not support setting the barcode image background color to transparent.

Solution

Convert the background color of the generated barcode image to transparent through image processing.

Sample code (for reference only):

import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

/**
 * Pass the **PixelMap** object generated by **createBarcode** and its background color to obtain a converted **PixelMap** object with a transparent background.
 *
 * @param {image.PixelMap} originalPixelMap - **PixelMap** object generated by **createBarcode**.
 * @param {number} backgroundColor - Hexadecimal background color defined in **CreateOptions**
 * @returns {Promise<image.PixelMap | undefined>} If the operation is successful, a new **PixelMap** object is returned. If the operation fails, **undefined** is returned.
 */
export async function convertBackgroundColorToTransparent(originalPixelMap: image.PixelMap,
  backgroundColor: number): Promise<image.PixelMap | undefined> {
  try {
    // Obtain image source information.
    const imageInfo: image.ImageInfo = await originalPixelMap.getImageInfo();

    // Create a buffer to store pixel data.
    const buffer: ArrayBuffer = new ArrayBuffer(originalPixelMap.getPixelBytesNumber());

    // Read pixel data to the buffer.
    originalPixelMap.readPixelsToBufferSync(buffer);

    // Initialize the options of the new **PixelMap**.
    const options: image.InitializationOptions = {
      editable: true,
      srcPixelFormat: imageInfo.pixelFormat,
      pixelFormat: imageInfo.pixelFormat,
      size: imageInfo.size
    };

    // Create an editable **PixelMap** object.
    let newPixelMap: image.PixelMap = image.createPixelMapSync(buffer, options);

    // Define the data area of the barcode image.
    const area: image.PositionArea = {
      pixels: new ArrayBuffer(imageInfo.size.height * imageInfo.size.width * 4), // Pixel data buffer.
      offset: 0, // Offset.
      stride: imageInfo.stride, // Spacing.
      region: { size: { height: imageInfo.size.height, width: imageInfo.size.width }, x: 0, y: 0 } // Area.
    };

    // Convert the area data to Uint8Array.
    let areaUint8Array: Uint8Array = new Uint8Array(area.pixels);
    let originalPixelMapUint8Array: Uint8Array = new Uint8Array(buffer);

    // Extract the values of the red, green, and blue channels from backgroundColor.
    const redBg: number = (backgroundColor >> 16) & 0xFF;
    const greenBg: number = (backgroundColor >> 8) & 0xFF;
    const blueBg: number = backgroundColor & 0xFF;

    // Traverse pixels.
    for (let i = 0; i < originalPixelMapUint8Array.length; i += 4) {
      const red: number = originalPixelMapUint8Array[i];
      const green: number = originalPixelMapUint8Array[i + 1];
      const blue: number = originalPixelMapUint8Array[i + 2];

      // Copy the red, green, and blue channels.
      areaUint8Array[i] = red;
      areaUint8Array[i + 1] = green;
      areaUint8Array[i + 2] = blue;

      // Check whether the color specified by the pixels is the same as the background color.
      if (red === redBg && green === greenBg && blue === blueBg) {
        areaUint8Array[i + 3] = 0; // Set the background color to transparent.
      } else {
        areaUint8Array[i + 3] = originalPixelMapUint8Array[i + 3]; // Retain the original transparency.
      }
    }

    // Write new pixel data.
    await newPixelMap.writePixels(area);

    // Return a new **PixelMap** object.
    return newPixelMap;
  } catch (err) {
    hilog.error(0x0001, 'CreateBarcode', `Failed to convertBackgroundColorToTransparent. Code: ${err.code}.`);
    return undefined;
  }
}