• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Pixel Map Operation
2
3To process a certain area in an image, you can perform pixel map 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** Pixel map operation
8![Pixel map operation](figures/bitmap-operation.png)
9
10## How to Develop
11
12Read [Image](../reference/apis/js-apis-image.md#pixelmap7) for APIs related to pixel map operations.
13
141. Complete [image decoding](image-decoding.md#how-to-develop) and obtain a **PixelMap** object.
15
162. Obtain information from the **PixelMap** object.
17
18   ```ts
19   // Obtain the total number of bytes of this pixel map.
20   let pixelBytesNumber = pixelMap.getPixelBytesNumber();
21   // Obtain the number of bytes per row of this pixel map.
22   let rowCount = pixelMap.getBytesNumberPerRow();
23   // 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.
24   let getDensity = pixelMap.getDensity();
25   ```
26
273. Read and modify the pixel data of the target area, and write the modified data back to the original image.
28
29   ```ts
30   // Scenario 1: Read the pixel data of the entire image and write the modified data to an array buffer.
31   const readBuffer = new ArrayBuffer(pixelBytesNumber);
32   pixelMap.readPixelsToBuffer(readBuffer).then(() => {
33     console.info('Succeeded in reading image pixel data.');
34   }).catch(error => {
35     console.error('Failed to read image pixel data. And the error is: ' + error);
36   })
37
38   // Scenario 2: Read the pixel data in a specified area and write the modified data to area.pixels.
39   const area = {
40     pixels: new ArrayBuffer(8),
41     offset: 0,
42     stride: 8,
43     region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
44   }
45   pixelMap.readPixels(area).then(() => {
46     console.info('Succeeded in reading the image data in the area.');
47   }).catch(error => {
48     console.error('Failed to read the image data in the area. And the error is: ' + error);
49   })
50
51   // The read image data can be used independently (by creating a pixel map) or modified as required.
52   // Write area.pixels to the specified area.
53   pixelMap.writePixels(area).then(() => {
54     console.info('Succeeded to write pixelMap into the specified area.');
55   })
56
57   // Write the image data result to a pixel map.
58   const writeColor = new ArrayBuffer(96);
59   pixelMap.writeBufferToPixels(writeColor, () => {});
60   ```
61