• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# PixelMap Operation (ArkTS)
2
3To process a certain area in an image, you can perform PixelMap operations, which are usually used to beautify the image.
4
5As shown in the figure below, the pixel data of a rectangle in an image is read, modified, and then written back to the corresponding area of the original image.
6
7**Figure 1** PixelMap operation
8
9![PixelMap operation](figures/bitmap-operation.png)
10
11## How to Develop
12
13Read [Image](../reference/apis-image-kit/js-apis-image.md#pixelmap7) for APIs related to PixelMap operations.
14
151. Complete [image decoding](image-decoding.md#how-to-develop) and obtain a **PixelMap** object.
16
172. Obtain information from the **PixelMap** object.
18
19   ```ts
20   import image from '@ohos.multimedia.image';
21   // Obtain the total number of bytes of this PixelMap object.
22   let pixelBytesNumber : number = pixelMap.getPixelBytesNumber();
23   // Obtain the number of bytes per row of this PixelMap object.p
24   let rowCount : number = pixelMap.getBytesNumberPerRow();
25   // Obtain the pixel density of the image. Pixel density refers to the number of pixels per inch of an image. A larger value of the pixel density indicates a finer image.
26   let getDensity : number = pixelMap.getDensity();
27   ```
28
293. Read and modify the pixel data of the target area, and write the modified data back to the original image.
30
31   ```ts
32   import {BusinessError} from '@ohos.base'
33   // Scenario 1: Read the pixel data of the entire image and write the modified data to an array buffer.
34   const readBuffer = new ArrayBuffer(pixelBytesNumber);
35   pixelMap.readPixelsToBuffer(readBuffer).then(() => {
36     console.info('Succeeded in reading image pixel data.');
37   }).catch((error : BusinessError) => {
38     console.error('Failed to read image pixel data. And the error is: ' + error);
39   })
40
41   // Scenario 2: Read the pixel data in a specified area and write the modified data to area.pixels.
42   const area : image.PositionArea = {
43     pixels: new ArrayBuffer(8),
44     offset: 0,
45     stride: 8,
46     region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
47   }
48   pixelMap.readPixels(area).then(() => {
49     console.info('Succeeded in reading the image data in the area.');
50   }).catch((error : BusinessError) => {
51     console.error('Failed to read the image data in the area. And the error is: ' + error);
52   })
53
54   // The read image data can be used independently (by creating a PixelMap object) or modified as required.
55   // Write area.pixels to the specified area.
56   pixelMap.writePixels(area).then(() => {
57     console.info('Succeeded to write pixelMap into the specified area.');
58   })
59
60   // Write the image data result to the PixelMap object.
61   const writeColor = new ArrayBuffer(96);
62   pixelMap.writeBufferToPixels(writeColor, () => {});
63   ```
64