目录

Image Editing Using PixelMap

Overview

In mobile app development, image editing is a common scenario for users, such as editing images in albums and applying filters to images on social media.

PixelMap is a core class in HarmonyOS that represents image pixel data. It provides an uncompressed bitmap format that allows you to directly read and write pixel data and obtain image information. It is the basis for image processing, transformation, and drawing. This document describes how to use PixelMap to edit images, such as obtaining image information, clipping, scaling, offsetting, rotating, flipping, setting transparency, and reading and writing pixel data.

The following table describes the related scenarios and key technologies.

  1. Basic image editing

    Description

    Scenario

    Key Technology

    Image information display

    View image metadata, including the image size, pixel format, and HDR attributes, to help users understand the basic attributes of the image before editing it.

    Obtain image metadata using getImageInfo().

    Image clipping by aspect ratio

    Clip images by aspect ratio to meet the requirements of different platforms, such as profile pictures (1:1), advertisements (4:3), and video thumbnails (16:9).

    Calculate the aspect ratio for image clipping, and use PixelMap.crop() for clipping.

    Image translation

    Adjust the image position horizontally or vertically for fine-tuning the composition.

    Calculate the horizontal and vertical offsets of the image, and use PixelMap.translate() to translate the image horizontally and vertically.

    Image rotation

    Rotate the image counterclockwise to correct the shooting angle deviation and adapt to different display orientations.

    Calculate the image rotation angle and call PixelMap.rotate() to rotate the image.

    Image flipping

    Flip the image horizontally to create a symmetrical effect, which is used for creative design and reflection effect production.

    Control the flip direction through variables, and call PixelMap.flipSync() to flip the image.

    Image scaling in proportion

    Scale the image in the range of 80% to 120% to adapt to different screen sizes of devices.

    Calculate the proportional scaling factor, and use PixelMap.scale() to scale the image.

  2. Image adjustment

    Description

    Scenario

    Key Technology

    Image brightness adjustment

    Adjust the overall brightness of an image using a slider. This is applicable to images with insufficient or excessive light.

    Process pixel-level RGB data using the linear scaling algorithm RGB_new = RGB x factor, and use the worker thread for asynchronous processing to avoid frame freezing.

    Image transparency adjustment

    Adjust the transparency of an image using a slider to create a semi-transparent overlay effect, which is used for UI masking or background blurring.

    Directly modify the alpha channel using the PixelMap.opacity() API.

    Image saturation adjustment

    Adjust the saturation of an image using a slider to enhance or reduce the color vividness, thereby adjusting the artistic style of the image.

    Process pixel-level RGB data using the brightness formula and saturation algorithm, and use the worker thread for asynchronous processing.

    Image filter adding

    Add preset filter effects to images for artistic creation and style processing.

    Create a filter image effect object using effectKit.createEffect() and add the filter effect using the corresponding API.

Image Information Display

[h2]When to Use

Obtain image information and display it on the page. The following figure shows the effect.

[h2]How to Implement

Use the getImageInfo() method of ImageSource to obtain information such as the image size, pixel format, color space, transparency, image format, and whether the image is HDR. Then, use the basic component to display the image information on the page.

[h2]How to Develop

  1. Create an ImageSource instance using image.createImageSource() and call the getImageInfo() method to obtain image information.
    this.imageSource = await createImageSourceFromResource(this.getUIContext());
    // ...
    this.imageSource.getImageInfo((err, imageInfo) => {
      if (err) {
        Logger.error(`Failed to get image info: code = ${err?.code}, message = ${err?.message}`);
        return;
      }
      Object.keys(imageInfo).forEach((key) => {
        if (key === 'size') {
          Object.keys(imageInfo[key]).forEach((chlKey) => {
            this.imageInfoArr.push({
              label: chlKey,
              value: imageInfo[key][chlKey]
            });
          });
        } else {
          this.imageInfoArr.push({
            label: key,
            value: imageInfo[key]
          })
        }
      });
    });
  2. Display the image information.
    List() {
      ForEach(this.imageInfoArr, (item: ImageInfoItem) => {
        ListItem() {
          Row() {
            Text(item.label)
              // ...
            Text(item.value + '')
              // ...
          }
          .width('100%')
          .height('100%')
          .justifyContent(FlexAlign.SpaceBetween)
          .padding({ left: 12, right: 12 })
        }
        .width('100%')
        .height(48)
      }, (item: ImageInfoItem) => item.label)
    }
    .divider({
      strokeWidth: 0.5,
      color: 'rgba(0,0,0,0.2)',
      startMargin: 12,
      endMargin: 12
    })
    // ...

Image Clipping by Aspect Ratio

[h2]When to Use

Clip an image by aspect ratio, such as 1:1, 4:3, or 16:9. The following figure shows the implementation effect.

[h2]How to Implement

Use the crop() method to clip an image based on the input size.

The value range of the image clipping size cannot exceed the width and height of the image.

[h2]How to Develop

  1. Customize the square() method to clip an image by aspect ratio 1:1.
    • width < height (portrait image): The clipping width and height are both the original width of the image. x = 0, and y is vertically centered.
    • width >= height (landscape image/square image): The clipping width and height are both the original height of the image. x is horizontally centered, and y = 0.
    /**
     * Crop image to 1:1 square ratio. The crop region is centered.
     *
     * @param pixelMap - The image to crop.
     * @param width - Original image width.
     * @param height - Original image height.
     */
    export async function square(pixelMap: PixelMap, width: number, height: number) {
      try {
        if (width < height) {
          await pixelMap.crop({
            size: {
              width: width,
              height: width
            },
            x: 0,
            y: Math.round((height - width) / CommonConstants.AVERAGE_WEIGHT_WIDTH)
          });
        } else {
          await pixelMap.crop({
            size: {
              width: height,
              height: height
            },
            x: Math.round((width - height) / CommonConstants.AVERAGE_WEIGHT_WIDTH),
            y: 0
          });
        }
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `square crop failed: ${error.code}, ${error.message}`);
      }
    }
  2. Customize the banner() method to clip an image by aspect ratio 4:3.
    1. width <= height (portrait image): clipping width = image width; clipping height = width x 3/4; x = 0, and y is vertically centered.
    2. width > height and width x 3/4 >= height (landscape image with a small height): clipping height = image height; clipping width = height/(3/4); y = 0, and x is horizontally centered.
    3. width > height but width x 3/4 < height (landscape image with a large height): clipping is performed based on the image width, which is the same as in case a.
    4. Call the cropCommon() method and execute pixelMap.crop() to clip the image.
    export async function cropCommon(pixelMap: PixelMap, cropWidth: number, cropHeight: number, cropPosition: RegionItem) {
      try {
        await pixelMap.crop({
          size: {
            width: cropWidth,
            height: cropHeight
          },
          x: cropPosition.x,
          y: cropPosition.y
        });
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `cropCommon failed: ${error.code}, ${error.message}`);
      }
    }
    /**
     * Crop image to 4:3 ratio. The crop region is centered.
     *
     * @param pixelMap - The image to crop.
     * @param width - Original image width.
     * @param height - Original image height.
     */
    export async function banner(pixelMap: PixelMap, width: number, height: number) {
      if (width <= height) {
        const cropWidth = width;
        const cropHeight = Math.floor(width * CommonConstants.CROP_RATE_4_3);
        const cropPosition = new RegionItem(0, Math.floor((height - cropHeight) / CommonConstants.AVERAGE_WEIGHT_WIDTH));
        await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
        return;
      }
      if (width * CommonConstants.CROP_RATE_4_3 >= height) {
        const cropWidth = Math.floor(height / CommonConstants.CROP_RATE_4_3);
        const cropHeight = height;
        const cropPosition = new RegionItem(Math.floor((width - cropWidth) / CommonConstants.AVERAGE_WEIGHT_WIDTH), 0);
        await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
        return;
      }
    
      const cropWidth = width;
      const cropHeight = Math.floor(width * CommonConstants.CROP_RATE_4_3);
      const cropPosition = new RegionItem(0, Math.floor((height - cropHeight) / CommonConstants.AVERAGE_WEIGHT_WIDTH));
      await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
    }
  3. Customize the rectangle() method to clip an image by aspect ratio 16:9. The implementation method is the same as that in 4:3 mode.
    /**
     * Crop image to 16:9 ratio. The crop region is centered.
     *
     * @param pixelMap - The image to crop.
     * @param width - Original image width.
     * @param height - Original image height.
     */
    export async function rectangle(pixelMap: PixelMap, width: number, height: number) {
      if (width <= height) {
        const cropWidth = width;
        const cropHeight = Math.floor(width * (CommonConstants.CROP_RATE_9_16));
        const cropPosition = new RegionItem(0, Math.floor((height - cropHeight) / CommonConstants.AVERAGE_WEIGHT_WIDTH));
        await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
        return;
      }
      if (width * (CommonConstants.CROP_RATE_9_16) >= height) {
        const cropWidth = Math.floor(height / (CommonConstants.CROP_RATE_9_16));
        const cropHeight = height;
        const cropPosition = new RegionItem(Math.floor((width - cropWidth) / CommonConstants.AVERAGE_WEIGHT_WIDTH), 0);
        await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
        return;
      }
    
      const cropWidth = width;
      const cropHeight = Math.floor(width * (CommonConstants.CROP_RATE_9_16));
      const cropPosition = new RegionItem(0, Math.floor((height - cropHeight) / CommonConstants.AVERAGE_WEIGHT_WIDTH));
      await cropCommon(pixelMap, cropWidth, cropHeight, cropPosition);
    }

Image Translation

[h2]When to Use

You can use a slider to adjust the image position horizontally or vertically. The following figure shows the implementation effect.

[h2]How to Implement

Use the translate() method to adjust the image position based on the input coordinates.

[h2]How to Develop

  1. In the onChange() event of the slider, pass the slider progress value and status.
    TabContent() {
      TranslateView({
        onTranslateChange: (value: number, mode: SliderChangeMode) => {
          this.editController?.handleTranslateChange(value, mode);
        }
      })
    }
    Slider({
      value: this.editState.currentTranslateData[this.editState.currentTranslateMode],
      step: 1,
      min: 0,
      max: 1000,
      // ...
    })
      // ...
      .onChange((value: number, mode: SliderChangeMode) => {
        if (this.onTranslateChange !== undefined) {
          this.onTranslateChange(value > 1000 ? 1000 : value, mode);
        }
      })
  2. When the sliding ends and the value changes, calculate the offset moveValue and update the state. Then, based on the translation direction (horizontal translation when currentTranslateMode is set to 0; otherwise, vertical translation), call translateImage() and pass the offset moveValue to perform translation.
    async handleTranslateChange(value: number, mode: SliderChangeMode): Promise<void> {
      if (mode === SliderChangeMode.End &&
        value !== this.editState.currentTranslateData[this.editState.currentTranslateMode]) {
        const moveValue: number =
          Math.round(value) - this.editState.currentTranslateData[this.editState.currentTranslateMode];
        this.editState.updateTranslateData(this.editState.currentTranslateMode, Math.round(value));
        if (this.editState.currentTranslateMode === 0) {
          // horizontal translation.
          await this.pixelMapManager.translateImage({ x: moveValue, y: 0 });
        } else {
          // vertical translation.
          await this.pixelMapManager.translateImage({ x: 0, y: moveValue });
        }
      }
    }
  3. In getStartEditPixelMap(), copy the PixelMap object based on the editing mode using cloneSync() and return the copied object.
    1. PixelMap-based start point: applicable to image clipping, adjustment (brightness/transparency/saturation), filter (black and white/highlight/flip/blurring), and scaling. The PixelMap is recalculated based on the same start point. For example, if the image brightness is adjusted from 50% to 80%, the calculation is based on the original image.
    2. PixelMap-based result: applicable to image rotation, flipping, and translation. The result is accumulated based on the previous editing result. For example, if an image is rotated from 90° to 180°, the rotation is performed again based on the result of the previous rotation.
    getStartEditPixelMap(mode: EditType): PixelMap | undefined {
      if (this.editMode !== mode) {
        this.editMode = mode;
        this.startEditPixelMap = this.finalEditPixelMap;
      }
      let target: PixelMap | undefined;
      switch (mode) {
        case EditType.CROP:
          target = this.startEditPixelMap;
          break;
        case EditType.MIRROR:
          target = this.finalEditPixelMap;
          break;
        case EditType.ROTATION:
          target = this.finalEditPixelMap;
          break;
        case EditType.FILTER:
          target = this.startEditPixelMap;
          break;
        case EditType.ADJUST:
          target = this.startEditPixelMap;
          break;
        case EditType.TRANSLATION:
          target = this.finalEditPixelMap;
          break;
        case EditType.SCALE:
          target = this.startEditPixelMap;
          break;
        default:
          target = this.finalEditPixelMap;
          break;
      }
      if (target !== null && target !== undefined) {
        return this.clonePixelMap(target);
      }
      return undefined;
    }
    // Copy the current Pixelmap object.
    clonePixelMap(pixelMap: PixelMap): PixelMap {
      try {
        return pixelMap.cloneSync();
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `${error.code}, ${error.message}`);
        return pixelMap;
      }
    }
  4. In the translateImage() method, obtain the PixelMap, call the translate() method to translate the image horizontally or vertically, and save the translation result. Pass the edited PixelMap to notifyPreviewUpdate() to notify the page to update the preview image, thereby changing the image position horizontally or vertically.
    async translateImage(moveValue: TranslateValue) {
      const px = this.getStartEditPixelMap(EditType.TRANSLATION);
      if (px === null || px === undefined) {
        return;
      }
      try {
        await px.translate(moveValue.x, moveValue.y); // Perform image offset.
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `translate failed: ${error.code}, ${error.message}`);
      }
      this.finalEditPixelMap = px; // Save the edited PixelMap.
      try {
        this.notifyPreviewUpdate(px); // Update Preview.
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `${error.code}, ${error.message}`);
      }
    }

Image Rotation

[h2]When to Use

Tap the image rotation button to change the image display orientation. The following figure shows the implementation effect.

[h2]How to Implement

Use the rotate() method to rotate the image based on the input angle.

[h2]How to Develop

  1. When the image rotation icon is tapped, the rotateImage() method is called to update the image rotation angle. The rotation angle is calculated as follows: Rotation angle = (Current angle – 90 + 360) % 360. This ensures that the image rotates 90° counterclockwise each time.
    rotateImage(): void {
      this.editState.rotationAngle = (this.editState.rotationAngle - 90 + 360) % 360;
      this.pixelMapManager.cropImage(this.editState.currentCropMode, this.editState.rotationAngle,
        this.editState.isMirrored);
    }
  2. In the cropImage() method, call applyTransforms() to execute the rotate() method to rotate the image based on the input rotation angle and update the preview image.
    async cropImage(proportion: CropType, rotationAngle: number, isMirrored: boolean) {
      // ...
    
      await this.applyTransforms(px, rotationAngle, isMirrored);
      this.finalEditPixelMap = px;
      this.notifyPreviewUpdate(px);
    }
    private async applyTransforms(px: PixelMap, rotationAngle: number, isMirrored: boolean): Promise<void> {
      if (rotationAngle !== 0) {
        try {
          await px.rotate(rotationAngle);
        } catch (error) {
          Logger.error(TAG, `there is a error in rotate process with ${error?.code}`);
        }
      }
      // ...
    }

Image Flipping

[h2]When to Use

Tap the flip icon to flip the image horizontally. The following figure shows the implementation effect.

[h2]How to Implement

Use the flipSync() method to flip the image based on the input condition.

[h2]How to Develop

  1. When the flip icon of an image is tapped, the mirrorImage() method is called to change the flip status of the image.
    mirrorImage(): void {
      this.editState.isMirrored = !this.editState.isMirrored;
      this.pixelMapManager.cropImage(this.editState.currentCropMode, this.editState.rotationAngle,
        this.editState.isMirrored);
    }
  2. In the cropImage() method, call applyTransforms() to execute the flipSync() method to pass (true, false) for horizontal flipping and re-render the image.
    async cropImage(proportion: CropType, rotationAngle: number, isMirrored: boolean) {
      if (this.originCropPixelMap !== null && this.originCropPixelMap !== undefined) {
        // ...
    
        await this.applyTransforms(px, rotationAngle, isMirrored);
        this.finalEditPixelMap = px;
        this.notifyPreviewUpdate(px);
      }
    }
    private async applyTransforms(px: PixelMap, rotationAngle: number, isMirrored: boolean): Promise<void> {
      // ...
      if (isMirrored) {
        try {
          px.flipSync(true, false);
        } catch (error) {
          Logger.error(TAG, `there is a error in mirror process with ${error?.code}`);
        }
      }
    }

Image Scaling in Proportion

[h2]When to Use

You can use a slider to scale an image up or down proportionally. The following figure shows the implementation effect.

[h2]How to Implement

Use the scale() method to scale the image based on the input width and height scaling factors.

[h2]How to Develop

  1. When the slider is dragged, the handleZoomChange() method is called. After the dragging ends and the value changes, the value is divided by 100 and passed to the editImageScale() method as the scaling factor.
    async handleZoomChange(value: number, mode: SliderChangeMode): Promise<void> {
      if (mode === SliderChangeMode.End && value !== this.editState.currentZoom) {
        await this.pixelMapManager.editImageScale(value / 100);
        this.editState.currentZoom = value;
      }
    }
  2. Call the scale() method to scale the image up or down and update the preview image.
    async editImageScale(scale: number) {
      const px = this.getStartEditPixelMap(EditType.SCALE);
      if (px === null || px === undefined) {
        return;
      }
      try {
        await px.scale(scale, scale);
      } catch (err) {
        let error = err as BusinessError;
        Logger.error(TAG, `${error.code}, ${error.message}`);
      }
      this.finalEditPixelMap = px;
      this.notifyPreviewUpdate(px);
    }

Image Brightness Adjustment

[h2]When to Use

Drag the slider to adjust the image brightness. The following figure shows the implementation effect.

[h2]How to Implement

The overall brightness of the image is changed by linearly scaling the RGB components of each pixel.

The corresponding formulas are as follows:

R_new = R_original x factor

G_new = G_original x factor

B_new = B_original x factor

factor = Current adjustment value/100

Principle description:

[h2]How to Develop

  1. Define the adjustBrightness() method to calculate the brightness value. Use Math.max(0, Math.min(255, Math.round(...))) to ensure that the RGB values are within the range of 0 to 255.
    function adjustBrightness(pixelData: Uint8ClampedArray, adjustedData: Uint8ClampedArray, i: number,
      factor: number): void {
      const r = pixelData[i] * factor;
      const g = pixelData[i + 1] * factor;
      const b = pixelData[i + 2] * factor;
    
      adjustedData[i] = Math.max(0, Math.min(255, Math.round(r)));
      adjustedData[i + 1] = Math.max(0, Math.min(255, Math.round(g)));
      adjustedData[i + 2] = Math.max(0, Math.min(255, Math.round(b)));
    }
  2. Define the execColorInfo() function to traverse the image pixels and call adjustBrightness() to calculate the brightness value based on the adjustment type.
    export function execColorInfo(bufferArray: ArrayBuffer, last: number, cur: number, hsvIndex: number) {
      // ...
    
      try {
        const pixelData = new Uint8ClampedArray(bufferArray);
        const adjustedData = new Uint8ClampedArray(pixelData.length);
        const bytesPerPixel = 4;
        const factor = cur / 100;
        for (let i = 0; i < pixelData.length; i += bytesPerPixel) {
          adjustedData[i + 3] = pixelData[i + 3];
    
          if (pixelData[i + 3] < 1) {
            continue;
          }
          if (hsvIndex === AdjustType.BRIGHTNESS) {
            adjustBrightness(pixelData, adjustedData, i, factor);
          }
          // ...
        }
        return adjustedData.buffer;
      } catch (error) {
        Logger.error(TAG, `Failed to set adjustedData: code = ${error?.code}, message = ${error?.message}`);
        return null;
      }
    }
  3. Process pixel operations in the worker thread and returns the processed buffer.
    workerPort.onmessage = (event: MessageEvents) => {
      // ...
      let bufferArray: ArrayBuffer = data.buf;
      let last: number = data.last;
      let cur: number = data.cur;
      let adjustType: AdjustType = data.adjustType;
      let buffer = execColorInfo(bufferArray, last, cur, adjustType);
      try {
        // Return the processed buffer.
        workerPort.postMessage(buffer);
      } catch (error) {
        Logger.error(TAG, `post message error: code = ${error?.code}, message = ${error?.message}`);
      }
    };
  4. In the PixelMapManager class:
    • Define the processAdjustWorker() method to obtain the pixel buffer and send it to the worker child thread to implement worker communication.
      private async processAdjustWorker(value: number, buffer: ArrayBuffer, adjustType: AdjustType): Promise<ArrayBuffer> {
        await this.adjustLock;
      
        return new Promise((resolve) => {
          this.adjustLock = new Promise<void>((release) => {
            const message = new MessageItem(buffer, CommonConstants.SLIDER_MAX, value, adjustType);
            try {
              this.adjustWorker.postMessage(message);
            } catch (error) {
              Logger.error(TAG, `postMessage failed, code is ${error.code}, message is ${error.message}`);
              release();
            }
            this.adjustWorker.onmessage = (event: MessageEvents) => {
              resolve(event.data);
              release();
            };
          });
        });
      }
    • Define the adjustImage() method, call processAdjustWorker() and pass the current brightness slider value, pixel buffer, and adjustment type (brightness), and write the processed buffer back to the PixelMap.
      async adjustImage(currentAdjustData: number[]) {
        // Obtain the cloned baseline pixel image.
        const px = this.getStartEditPixelMap(EditType.ADJUST);
        if (px === null || px === undefined) {
          return;
        }
        let buffer = new ArrayBuffer(px.getPixelBytesNumber());
        await px.readPixelsToBuffer(buffer).catch((err: BusinessError) => {
          Logger.error(TAG, `readPixelsToBuffer failed: ${err.code}, ${err.message}`);
        });
        if (!buffer) {
          return;
        }
        if (currentAdjustData[AdjustType.BRIGHTNESS] !== CommonConstants.SLIDER_MAX) {
          buffer = await this.processAdjustWorker(
            currentAdjustData[AdjustType.BRIGHTNESS],
            buffer,
            AdjustType.BRIGHTNESS
          );
          try {
            px.writeBufferToPixelsSync(buffer); // Write the processed buffer back to Pixelmap.
          } catch (err) {
            let error = err as BusinessError;
            Logger.error(TAG, `${error.code}, ${error.message}`);
          }
        }
        // ...
        this.finalEditPixelMap = px; // Save edited pixelMap.
        this.notifyPreviewUpdate(px); // Update Preview.
      }
  5. Define the sliderChange() method and execute adjustImage(). Call sliderChange() in the onChange() event of the Slider component. This event is triggered when the user lifts their fingers, preventing frequent calculations and allowing for brightness adjustment.
    async sliderChange(value: number, mode: SliderChangeMode) {
      if ((mode === SliderChangeMode.End) && (value !== this.editState.currentAdjustData[this.currentAdjustType])) {
        const roundedValue = Math.round(value);
        this.editState.currentAdjustData[this.currentAdjustType] = roundedValue;
        this.paramValues[this.currentAdjustType] = roundedValue;
        this.deviceListDialogController.open();
        try {
          await this.pixelMapManager?.adjustImage(this.paramValues);
        } catch (err) {
          let error = err as BusinessError;
          Logger.error('SliderCustom', `adjustImage failed: code = ${error?.code}, message = ${error?.message}`);
        } finally {
          this.deviceListDialogController.close();
        }
      }
    }
    Slider({
      value: this.editState.currentAdjustData[this.currentAdjustType],
      step: CommonConstants.SLIDER_STEP,
      min: this.min,
      max: this.max,
      // ...
    })
      // ...
      .onChange((value: number, mode: SliderChangeMode) => {
        this.sliderChange(value > this.max ? this.max : value, mode);
      })

Image Transparency Adjustment

[h2]When to Use

Drag the slider to adjust the image transparency. The following figure shows the implementation effect.

[h2]How to Implement

Set the transparency of the PixelMap using opacity(). The transparency value is obtained through normalization of the slider value: opacity = sliderValue/100.

[h2]How to Develop

  1. Use the opacity() method of the PixelMap to adjust the transparency and update the preview.
    async adjustImage(currentAdjustData: number[]) {
      // Obtain the cloned baseline pixel image.
      const px = this.getStartEditPixelMap(EditType.ADJUST);
      if (px === null || px === undefined) {
        return;
      }
      let buffer = new ArrayBuffer(px.getPixelBytesNumber());
      await px.readPixelsToBuffer(buffer).catch((err: BusinessError) => {
        Logger.error(TAG, `readPixelsToBuffer failed: ${err.code}, ${err.message}`);
      });
      if (!buffer) {
        return;
      }
      // ...
      if (currentAdjustData[AdjustType.OPACITY] !== CommonConstants.SLIDER_MAX) {
        const opacity = currentAdjustData[AdjustType.OPACITY] / CommonConstants.SLIDER_MAX;
        try {
          await px.opacity(opacity).catch((err: BusinessError) => {
            Logger.error(TAG, `opacity failed: ${err.code}, ${err.message}`);
          });
        } catch (err) {
          let error = err as BusinessError;
          Logger.error(TAG, `${error.code}, ${error.message}`);
        }
      }
      this.finalEditPixelMap = px; // Save edited pixelMap.
      this.notifyPreviewUpdate(px); // Update Preview.
    }
  2. Call sliderChange() in the onChange() event of the Slider component to adjust the transparency. For details, see the development procedure for image brightness adjustment.

Image Saturation Adjustment

[h2]When to Use

Drag the slider to adjust the image saturation. The following figure shows the implementation effect.

[h2]How to Implement

Adjust the distance between a pixel and its grayscale value to change the color saturation.

The corresponding formulas are as follows:

  1. Calculate the pixel luminance:

    luminance = 0.2126 x r + 0.7152 x g + 0.0722 x b

  2. Adjust the RGB components (factor = Current value of the slider/100):

    adjustedR = luminance + (r - luminance) x factor

    adjustedG = luminance + (g - luminance) x factor

    adjustedB = luminance + (b - luminance) x factor

Principle description:

Luminance coefficients: 0.2126, 0.7152, and 0.0722 are the ITU-R BT.709 luminance conversion coefficients.

[h2]How to Develop

  1. Define the adjustSaturation() method to adjust the image saturation. Divide the RGB values by 255 to normalize them to the range [0, 1] for calculation. Use the standard luminance formula to calculate the luminance, multiply the calculation result by 255, and round it to a value within the range of 0 to 255.
    function adjustSaturation(pixelData: Uint8ClampedArray, adjustedData: Uint8ClampedArray, i: number,
      factor: number): void {
      const r = pixelData[i] / 255;
      const g = pixelData[i + 1] / 255;
      const b = pixelData[i + 2] / 255;
    
      const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
    
      const adjustedR = luminance + (r - luminance) * factor;
      const adjustedG = luminance + (g - luminance) * factor;
      const adjustedB = luminance + (b - luminance) * factor;
    
      adjustedData[i] = Math.max(0, Math.min(255, Math.round(adjustedR * 255)));
      adjustedData[i + 1] = Math.max(0, Math.min(255, Math.round(adjustedG * 255)));
      adjustedData[i + 2] = Math.max(0, Math.min(255, Math.round(adjustedB * 255)));
    }
  2. In execColorInfo(), call adjustSaturation() to adjust the saturation of the image based on the adjustment type.
    export function execColorInfo(bufferArray: ArrayBuffer, last: number, cur: number, hsvIndex: number) {
      // ...
    
      try {
        const pixelData = new Uint8ClampedArray(bufferArray);
        const adjustedData = new Uint8ClampedArray(pixelData.length);
        const bytesPerPixel = 4;
        const factor = cur / 100;
        for (let i = 0; i < pixelData.length; i += bytesPerPixel) {
          adjustedData[i + 3] = pixelData[i + 3];
    
          if (pixelData[i + 3] < 1) {
            continue;
          }
          // ...
          if (hsvIndex === AdjustType.SATURATION) {
            adjustSaturation(pixelData, adjustedData, i, factor);
          }
        }
        return adjustedData.buffer;
      } catch (error) {
        Logger.error(TAG, `Failed to set adjustedData: code = ${error?.code}, message = ${error?.message}`);
        return null;
      }
    }
  3. For details about worker thread processing and worker communication, see the development procedure for image brightness adjustment.
  4. In the adjustImage() method, obtain the pixel data of the PixelMap to the buffer, call the method for processing image saturation, and update the preview image.
    async adjustImage(currentAdjustData: number[]) {
      // Obtain the cloned baseline pixel image.
      const px = this.getStartEditPixelMap(EditType.ADJUST);
      if (px === null || px === undefined) {
        return;
      }
      let buffer = new ArrayBuffer(px.getPixelBytesNumber());
      await px.readPixelsToBuffer(buffer).catch((err: BusinessError) => {
        Logger.error(TAG, `readPixelsToBuffer failed: ${err.code}, ${err.message}`);
      });
      if (!buffer) {
        return;
      }
      // ...
      if (currentAdjustData[AdjustType.SATURATION] !== CommonConstants.SLIDER_MAX) {
        try {
          buffer = await this.processAdjustWorker(
            currentAdjustData[AdjustType.SATURATION],
            buffer,
            AdjustType.SATURATION
          );
          // Write the processed buffer back to Pixelmap.
          px.writeBufferToPixelsSync(buffer);
        } catch (err) {
          let error = err as BusinessError;
          Logger.error(TAG, `${error.code}, ${error.message}`);
        }
      }
      // ...
      this.finalEditPixelMap = px; // Save edited pixelMap.
      this.notifyPreviewUpdate(px); // Update Preview.
    }
  5. Call sliderChange() in the onChange() event of the Slider component to adjust the saturation. For details, see step 5 in the development procedure for image brightness adjustment.

Image Black-and-White Filter Adding

[h2]When to Use

Select the black-and-white filter to display the image in black-and-white effect. The following figure shows the implementation effect.

[h2]How to Implement

Create a filter effecter using effectKit.createEffect() and call the grayscale() method to add the grayscale effect to the image.

[h2]How to Develop

  1. Obtain the PixelMap to be edited, create a filter effect object using effectKit.createEffect(), and apply the corresponding effect based on the input filter type.
    When type is set to FilterType.GRAYSCALE, call grayscale() to add the grayscale effect to the image, obtain the processed PixelMap using getEffectPixelMap(), and update the preview using notifyPreviewUpdate().
    async handleFilter(type: FilterType) {
      // Obtain the cloned baseline pixel image.
      let startMap = this.getStartEditPixelMap(EditType.FILTER);
      if (startMap === null || startMap === undefined) {
        return;
      }
      let px: PixelMap = startMap;
      let filter = effectKit.createEffect(px); // Create filter object.
    
      switch (type) {
        case FilterType.GRAYSCALE:
          px = await filter.grayscale().getEffectPixelMap();
          break;
        // ...
        default:
          break;
      }
      this.notifyPreviewUpdate(px); // Update Preview.
      this.finalEditPixelMap = px; // Save edited pixelMap.
    }
  2. In the tap event, call handleFilter() and pass the index of the currently tapped item to apply the black-and-white filter effect.
    ForEach(this.filterData, (item: filterDataType, index: number) => {
      Flex({
        direction: this.currentBreakpoint === 'lg' ? FlexDirection.Row : FlexDirection.Column,
        alignItems: ItemAlign.Center
      }) {
        Image(this.filterThumbnails[index])
          // ...
    
        Text(item.title)
          // ...
      }
      // ...
      .onClick(() => {
        this.pixelMapManager?.handleFilter(index);
        this.editState.currentFilterMode = index;
      })
    }, (item: filterDataType) => item.key)

Image Highlight Filter Adding

[h2]When to Use

Select the highlight filter to display the image in highlight effect. The following figure shows the implementation effect.

[h2]How to Implement

Use the effectKit effecter to call the brightness() method to add the highlight effect to the image.

[h2]How to Develop

  1. When type is set to FilterType.BRIGHTNESS, call brightness() to add the highlight effect to the image, obtain the processed PixelMap, and update the preview image.
    async handleFilter(type: FilterType) {
      // Obtain the cloned baseline pixel image.
      let startMap = this.getStartEditPixelMap(EditType.FILTER);
      if (startMap === null || startMap === undefined) {
        return;
      }
      let px: PixelMap = startMap;
      let filter = effectKit.createEffect(px); // Create filter object.
    
      switch (type) {
        // ...
        case FilterType.BRIGHTNESS:
          px = await filter.brightness(0.7).getEffectPixelMap();
          break;
        // ...
        default:
          break;
      }
      this.notifyPreviewUpdate(px); // Update Preview.
      this.finalEditPixelMap = px; // Save edited pixelMap.
    }
  2. In the tap event, call handleFilter() and pass the index of the currently tapped item to apply the highlight filter effect. For details, see step 2 in the development procedure for the black-and-white filter adding.

Image Inversion Filter Adding

[h2]When to Use

Select the inversion filter to display the image in inversion effect. The following figure shows the implementation effect.

[h2]How to Implement

Use the effectKit effecter to call the invert() method to add the inversion effect to the image.

[h2]How to Develop

  1. When type is set to FilterType.INVERT, call invert() to add the inversion effect to the image, obtain the processed PixelMap, and update the preview image.
    async handleFilter(type: FilterType) {
      // Obtain the cloned baseline pixel image.
      let startMap = this.getStartEditPixelMap(EditType.FILTER);
      if (startMap === null || startMap === undefined) {
        return;
      }
      let px: PixelMap = startMap;
      let filter = effectKit.createEffect(px); // Create filter object.
    
      switch (type) {
        // ...
        case FilterType.INVERT:
          px = await filter.invert().getEffectPixelMap();
          break;
        // ...
        default:
          break;
      }
      this.notifyPreviewUpdate(px); // Update Preview.
      this.finalEditPixelMap = px; // Save edited pixelMap.
    }
  2. In the tap event, call handleFilter() and pass the index of the currently tapped item to apply the inversion filter effect. For details, see step 2 in the development procedure for the black-and-white filter adding.

Image Blur Filter Adding

[h2]When to Use

Select the blur filter to display the image in blur effect. The following figure shows the implementation effect.

[h2]How to Implement

Use the effectKit effecter to call the blur() method to add the blur effect to the image.

[h2]How to Develop

  1. When type is set to FilterType.BLUR, call blur() to add the blur effect to the image, obtain the processed PixelMap, and update the preview image.
    async handleFilter(type: FilterType) {
      // Obtain the cloned baseline pixel image.
      let startMap = this.getStartEditPixelMap(EditType.FILTER);
      if (startMap === null || startMap === undefined) {
        return;
      }
      let px: PixelMap = startMap;
      let filter = effectKit.createEffect(px); // Create filter object.
    
      switch (type) {
        // ...
        case FilterType.BLUR:
          px = await filter.blur(5).getEffectPixelMap();
          break;
        default:
          break;
      }
      this.notifyPreviewUpdate(px); // Update Preview.
      this.finalEditPixelMap = px; // Save edited pixelMap.
    }
  2. In the tap event, call handleFilter() and pass the index of the currently tapped item to apply the blur filter effect. For details, see step 2 in the development procedure for the black-and-white filter adding.

Sample Code