@ohos.multimedia.image (Image Processing)
The Image module provides APIs for image processing. You can use the APIs to create a PixelMap object with specified properties or read pixels of an image (or even in a region of an image).
NOTE
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Since API version 12, the APIs of this module are supported in ArkTS widgets.
Modules to Import
import { image } from '@kit.ImageKit';
image.createPicture13+
createPicture(mainPixelmap : PixelMap): Picture
Creates a Picture object based on a main PixelMap.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mainPixelmap | PixelMap | Yes | Main PixelMap. |
Return value
| Type | Description |
|---|---|
| Picture | Picture object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types.3.Parameter verification failed. |
Example
import { image } from '@kit.ImageKit';
async function CreatePicture() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("test.jpg");
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
if (pictureObj != null) {
console.info('Create picture succeeded');
} else {
console.info('Create picture failed');
}
}
image.createPictureFromParcel13+
createPictureFromParcel(sequence: rpc.MessageSequence): Picture
Creates a Picture object from a MessageSequence object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sequence | rpc.MessageSequence | Yes | MessageSequence object that stores the Picture information. |
Return value
| Type | Description |
|---|---|
| Picture | Picture object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types.3.Parameter verification failed. |
| 62980097 | IPC error. |
Example
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
class MySequence implements rpc.Parcelable {
picture: image.Picture | null = null;
constructor(conPicture: image.Picture) {
this.picture = conPicture;
}
marshalling(messageSequence: rpc.MessageSequence) {
if(this.picture != null) {
this.picture.marshalling(messageSequence);
console.info('Marshalling success !');
return true;
} else {
console.info('Marshalling failed !');
return false;
}
}
unmarshalling(messageSequence : rpc.MessageSequence) {
this.picture = image.createPictureFromParcel(messageSequence);
this.picture.getMainPixelmap().getImageInfo().then((imageInfo : image.ImageInfo) => {
console.info('Unmarshalling to get mainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
}).catch((error: BusinessError) => {
console.error('Unmarshalling failed error.code: ${error.code} ,error.message: ${error.message}');
});
return true;
}
}
async function Marshalling_UnMarshalling() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("test.jpg");
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
if (pictureObj != null) {
let parcelable: MySequence = new MySequence(pictureObj);
let data: rpc.MessageSequence = rpc.MessageSequence.create();
// marshalling.
data.writeParcelable(parcelable);
let ret: MySequence = new MySequence(pictureObj);
// unmarshalling.
data.readParcelable(ret);
} else {
console.info('PictureObj is null');
}
}
image.createPixelMap8+
createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise<PixelMap>
Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| colors | ArrayBuffer | Yes | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by InitializationOptions.srcPixelFormat. NOTE: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel. |
| options | InitializationOptions | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable. |
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. If the size of the created PixelMap exceeds that of the original image, the PixelMap size of the original image is returned. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePixelMap() {
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
console.info('Succeeded in creating pixelmap.');
}).catch((error: BusinessError) => {
console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
})
}
image.createPixelMap8+
createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback<PixelMap>): void
Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| colors | ArrayBuffer | Yes | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by InitializationOptions.srcPixelFormat. NOTE: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel. |
| options | InitializationOptions | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable. |
| callback | AsyncCallback<PixelMap> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the PixelMap object obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePixelMap() {
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (error: BusinessError, pixelMap: image.PixelMap) => {
if(error) {
console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in creating pixelmap.');
}
})
}
image.createPixelMapFromParcel11+
createPixelMapFromParcel(sequence: rpc.MessageSequence): PixelMap
Creates a PixelMap object from a MessageSequence object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sequence | rpc.MessageSequence | Yes | MessageSequence object that stores the PixelMap information. |
Return value
| Type | Description |
|---|---|
| PixelMap | Returns a PixelMap object if the operation is successful; throws an error otherwise. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | Operation failed |
| 62980097 | IPC error. |
| 62980115 | Invalid input parameter |
| 62980105 | Failed to get the data |
| 62980177 | Abnormal API environment |
| 62980178 | Failed to create the PixelMap |
| 62980179 | Abnormal buffer size |
| 62980180 | FD mapping failed |
| 62980246 | Failed to read the PixelMap |
Example
import { image } from '@kit.ImageKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
class MySequence implements rpc.Parcelable {
pixel_map: image.PixelMap;
constructor(conPixelmap: image.PixelMap) {
this.pixel_map = conPixelmap;
}
marshalling(messageSequence: rpc.MessageSequence) {
this.pixel_map.marshalling(messageSequence);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence) {
try {
this.pixel_map = image.createPixelMapFromParcel(messageSequence);
} catch(e) {
let error = e as BusinessError;
console.error(`createPixelMapFromParcel error. code is ${error.code}, message is ${error.message}`);
return false;
}
return true;
}
}
async function CreatePixelMapFromParcel() {
const color: ArrayBuffer = new ArrayBuffer(96);
let bufferArr: Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = 0x80;
}
let opts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.BGRA_8888,
size: { height: 4, width: 6 },
alphaType: image.AlphaType.UNPREMUL
}
let pixelMap: image.PixelMap | undefined = undefined;
image.createPixelMap(color, opts).then((srcPixelMap: image.PixelMap) => {
pixelMap = srcPixelMap;
})
if (pixelMap != undefined) {
// Implement serialization.
let parcelable: MySequence = new MySequence(pixelMap);
let data: rpc.MessageSequence = rpc.MessageSequence.create();
data.writeParcelable(parcelable);
// Implement deserialization to obtain data through the RPC.
let ret: MySequence = new MySequence(pixelMap);
data.readParcelable(ret);
// Obtain the PixelMap object.
let unmarshPixelmap = ret.pixel_map;
}
}
image.createPixelMapFromSurface11+
createPixelMapFromSurface(surfaceId: string, region: Region): Promise<PixelMap>
Creates a PixelMap object based on the surface ID and region information. The size of the region is specified by Region.size. This API uses a promise to return the result.
NOTE
When working with foldable devices, switching between folded and unfolded states may cause the API call to fail due to the rotation angle of surface. To address this, you need to adjust the width and height according to the rotation angle.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| surfaceId | string | Yes | Surface ID, which can be obtained through the preview component, for example, XComponent. |
| region | Region | Yes | Region information. The width and height in Region.size must be the same as those of the preview stream. |
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980115 | If the image parameter invalid. |
| 62980105 | Failed to get the data |
| 62980178 | Failed to create the PixelMap |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePixelMapFromSurface(surfaceId: string) {
let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
image.createPixelMapFromSurface(surfaceId, region).then(() => {
console.info('Succeeded in creating pixelmap from Surface');
}).catch((error: BusinessError) => {
console.error(`Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
});
}
image.createPixelMapFromSurfaceSync12+
createPixelMapFromSurfaceSync(surfaceId: string, region: Region): PixelMap
Creates a PixelMap object based on the surface ID and region information. This API returns the result synchronously. The size of the region is specified by Region.size.
NOTE
When working with foldable devices, switching between folded and unfolded states may cause the API call to fail due to the rotation angle of surface. To address this, you need to adjust the width and height according to the rotation angle.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| surfaceId | string | Yes | Surface ID, which can be obtained through the preview component, for example, XComponent. |
| region | Region | Yes | Region information. The width and height in Region.size must be the same as those of the preview stream. |
Return value
| Type | Description |
|---|---|
| PixelMap | Returns a PixelMap object if the operation is successful; throws an error otherwise. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980105 | Failed to get the data |
| 62980178 | Failed to create the PixelMap |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Demo(surfaceId: string) {
let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
let pixelMap : image.PixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region);
return pixelMap;
}
image.createPixelMapSync12+
createPixelMapSync(colors: ArrayBuffer, options: InitializationOptions): PixelMap
Creates a PixelMap object with the default BGRA_8888 format and specified pixel properties. This API returns the result synchronously.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| colors | ArrayBuffer | Yes | Buffer for storing the pixel data. It is used to initialize the pixels of the PixelMap. Before initialization, the pixel format in the buffer must be specified by InitializationOptions.srcPixelFormat. NOTE: The length of the buffer required for storing the pixel data is determined by multiplying the width, height, and the number of bytes per pixel. |
| options | InitializationOptions | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable. |
Return value
| Type | Description |
|---|---|
| PixelMap | Returns a PixelMap object if the operation is successful; throws an error otherwise. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePixelMapSync() {
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
let pixelMap : image.PixelMap = image.createPixelMapSync(color, opts);
return pixelMap;
}
image.createPixelMapSync12+
createPixelMapSync(options: InitializationOptions): PixelMap
Creates a PixelMap object with the specified pixel properties. This API returns the result synchronously.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | InitializationOptions | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable. |
Return value
| Type | Description |
|---|---|
| PixelMap | Returns a PixelMap object if the operation is successful; throws an error otherwise. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePixelMapSync() {
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
let pixelMap : image.PixelMap = image.createPixelMapSync(opts);
return pixelMap;
}
image.createPremultipliedPixelMap12+
createPremultipliedPixelMap(src: PixelMap, dst: PixelMap, callback: AsyncCallback<void>): void
Converts a non-premultiplied alpha of a PixelMap to a premultiplied one and stores the converted data to a target PixelMap. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | PixelMap | Yes | Source PixelMap object. |
| dst | PixelMap | Yes | Target PixelMap object. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980103 | The image data is not supported |
| 62980246 | Failed to read the pixelMap |
| 62980248 | Pixelmap not allow modify |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePremultipliedPixelMap() {
const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 255;
bufferArr[i+2] = 122;
bufferArr[i+3] = 122;
}
let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
let srcPixelmap = image.createPixelMapSync(color, optsForUnpre);
let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
let dstPixelMap = image.createPixelMapSync(optsForPre);
image.createPremultipliedPixelMap(srcPixelmap, dstPixelMap, (error: BusinessError) => {
if(error) {
console.error(`Failed to convert pixelmap. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in converting pixelmap.');
}
})
}
image.createPremultipliedPixelMap12+
createPremultipliedPixelMap(src: PixelMap, dst: PixelMap): Promise<void>
Converts a non-premultiplied alpha of a PixelMap to a premultiplied one and stores the converted data to a target PixelMap. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | PixelMap | Yes | Source PixelMap object. |
| dst | PixelMap | Yes | Target PixelMap object. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980103 | The image data is not supported |
| 62980246 | Failed to read the pixelMap |
| 62980248 | Pixelmap not allow modify |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreatePremultipliedPixelMap() {
const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 255;
bufferArr[i+2] = 122;
bufferArr[i+3] = 122;
}
let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
let srcPixelmap = image.createPixelMapSync(color, optsForUnpre);
let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
let dstPixelMap = image.createPixelMapSync(optsForPre);
image.createPremultipliedPixelMap(srcPixelmap, dstPixelMap).then(() => {
console.info('Succeeded in converting pixelmap.');
}).catch((error: BusinessError) => {
console.error(`Failed to convert pixelmap. code is ${error.code}, message is ${error.message}`);
})
}
image.createUnpremultipliedPixelMap12+
createUnpremultipliedPixelMap(src: PixelMap, dst: PixelMap, callback: AsyncCallback<void>): void
Converts a premultiplied alpha of a PixelMap to a non-premultiplied one and stores the converted data to a target PixelMap. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | PixelMap | Yes | Source PixelMap object. |
| dst | PixelMap | Yes | Target PixelMap object. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980103 | The image data is not supported |
| 62980246 | Failed to read the pixelMap |
| 62980248 | Pixelmap not allow modify |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreateUnpremultipliedPixelMap() {
const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 255;
bufferArr[i+2] = 122;
bufferArr[i+3] = 122;
}
let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
let srcPixelmap = image.createPixelMapSync(color, optsForPre);
let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
let dstPixelMap = image.createPixelMapSync(optsForUnpre);
image.createUnpremultipliedPixelMap(srcPixelmap, dstPixelMap, (error: BusinessError) => {
if(error) {
console.error(`Failed to convert pixelmap. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in converting pixelmap.');
}
})
}
image.createUnpremultipliedPixelMap12+
createUnpremultipliedPixelMap(src: PixelMap, dst: PixelMap): Promise<void>
Converts a premultiplied alpha of a PixelMap to a non-premultiplied one and stores the converted data to a target PixelMap. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | PixelMap | Yes | Source PixelMap object. |
| dst | PixelMap | Yes | Target PixelMap object. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 62980103 | The image data is not supported. |
| 62980246 | Failed to read the pixelMap. |
| 62980248 | Pixelmap not allow modify. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreateUnpremultipliedPixelMap() {
const color: ArrayBuffer = new ArrayBuffer(16); // 16 is the size of the pixel buffer to create. The value is calculated as follows: height * width * 4.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 255;
bufferArr[i+2] = 122;
bufferArr[i+3] = 122;
}
let optsForPre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.PREMUL}
let srcPixelmap = image.createPixelMapSync(color, optsForPre);
let optsForUnpre: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 2, width: 2 } , alphaType: image.AlphaType.UNPREMUL}
let dstPixelMap = image.createPixelMapSync(optsForUnpre);
image.createUnpremultipliedPixelMap(srcPixelmap, dstPixelMap).then(() => {
console.info('Succeeded in converting pixelmap.');
}).catch((error: BusinessError) => {
console.error(`Failed to convert pixelmap. code is ${error.code}, message is ${error.message}`);
})
}
Picture13+
An image that contains special information can be decoded into a picture object, which generally contains the main picture, auxiliary picture, and metadata. The main picture contains most information about the image and is mainly used to render the image. The auxiliary picture is used to store data related to but different from the main picture, revealing more comprehensive details. The metadata is generally used to store information about the image file. The picture object class is used to read or write picture objects. Before calling any API in Picture, you must use createPicture to create a Picture object.
Properties
System capability: SystemCapability.Multimedia.Image.Core
getMainPixelmap13+
getMainPixelmap(): PixelMap
Obtains the PixelMap object of the main picture. This API returns the result synchronously.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| PixelMap | PixelMap object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function GetMainPixelmap() {
let funcName = "getMainPixelmap";
if (pictureObj != null) {
let mainPixelmap: image.PixelMap = pictureObj.getMainPixelmap();
if (mainPixelmap != null) {
mainPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo != null) {
console.info('GetMainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
}
}).catch((error: BusinessError) => {
console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
});
}
} else {
console.info('PictureObj is null');
}
}
getHdrComposedPixelmap13+
getHdrComposedPixelmap(): Promise<PixelMap>
Generates a High Dynamic Range (HDR) image and obtains its PixelMap object. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 7600901 | Unknown error. |
| 7600201 | Unsupported operation. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function GetHdrComposedPixelmap() {
let funcName = "getHdrComposedPixelmap";
if (pictureObj != null) { // An HDR image is contained.
let hdrComposedPixelmap: image.PixelMap = await pictureObj.getHdrComposedPixelmap();
if (hdrComposedPixelmap != null) {
hdrComposedPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo != null) {
console.info('GetHdrComposedPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
}
}).catch((error: BusinessError) => {
console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
});
}
} else {
console.info('PictureObj is null');
}
}
getGainmapPixelmap13+
getGainmapPixelmap(): PixelMap | null
Obtains the PixelMap object of the gain map.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| PixelMap | null | PixelMap object obtained. If there is no PixelMap object, null is returned. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function GetGainmapPixelmap() {
let funcName = "getGainmapPixelmap";
if (pictureObj != null) { // A gain map is contained.
let gainPixelmap: image.PixelMap | null = pictureObj.getGainmapPixelmap();
if (gainPixelmap != null) {
gainPixelmap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo != null) {
console.info('GetGainmapPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
} else {
console.info('GainPixelmap is null');
}
}).catch((error: BusinessError) => {
console.error(funcName, 'Failed error.code: ${error.code} ,error.message: ${error.message}');
});
} else {
console.info('GainPixelmap is null');
}
} else {
console.info('PictureObj is null');
}
}
setAuxiliaryPicture13+
setAuxiliaryPicture(type: AuxiliaryPictureType, auxiliaryPicture: AuxiliaryPicture): void
Sets an auxiliary picture.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | AuxiliaryPictureType | Yes | Type of the auxiliary picture. |
| auxiliaryPicture | AuxiliaryPicture | Yes | AuxiliaryPicture object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
Example
import { image } from '@kit.ImageKit';
async function SetAuxiliaryPicture() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let pixelMap: image.PixelMap = await imageSource.createPixelMap();
let auxPicture: image.Picture = image.createPicture(pixelMap);
if (auxPicture != null) {
console.info('Create picture succeeded');
} else {
console.info('Create picture failed');
}
if (pictureObj != null) {
let type: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
let auxPictureObj: image.AuxiliaryPicture | null = await auxPicture.getAuxiliaryPicture(type);
if (auxPictureObj != null) {
pictureObj.setAuxiliaryPicture(type, auxPictureObj);
}
}
}
getAuxiliaryPicture13+
getAuxiliaryPicture(type: AuxiliaryPictureType): AuxiliaryPicture | null
Obtains an auxiliary picture by type.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | AuxiliaryPictureType | Yes | Type of the auxiliary picture. |
Return value
| Type | Description |
|---|---|
| AuxiliaryPicture | null | AuxiliaryPicture object. If there is no AuxiliaryPicture object, null is returned. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
Example
import { image } from '@kit.ImageKit';
async function GetAuxiliaryPicture() {
if (pictureObj != null) {
let type: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(type);
}
}
setMetadata13+
setMetadata(metadataType: MetadataType, metadata: Metadata): Promise<void>
Sets the metadata for this Picture object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| metadataType | MetadataType | Yes | Metadata type. |
| metadata | Metadata | Yes | Metadata object. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7600202 | Unsupported metadata. Possible causes: Unsupported metadata type. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function SetPictureObjMetadata() {
const exifContext = getContext();
const exifResourceMgr = exifContext.resourceManager;
const exifRawFile = await exifResourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
let exifOps: image.SourceOptions = {
sourceDensity: 98,
}
let exifImageSource: image.ImageSource = image.createImageSource(exifRawFile.buffer as ArrayBuffer, exifOps);
let exifCommodityPixelMap: image.PixelMap = await exifImageSource.createPixelMap();
let exifPictureObj: image.Picture = image.createPicture(exifCommodityPixelMap);
if (exifPictureObj != null) {
console.info('Create picture succeeded');
} else {
console.info('Create picture failed');
}
if (pictureObj != null) {
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let exifMetaData: image.Metadata = await exifPictureObj.getMetadata(metadataType);
pictureObj.setMetadata(metadataType, exifMetaData).then(() => {
console.info('Set metadata success');
}).catch((error: BusinessError) => {
console.error('Failed to set metadata. error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
});
} else {
console.info('PictureObj is null');
}
}
getMetadata13+
getMetadata(metadataType: MetadataType): Promise<Metadata>
Obtains the metadata of this Picture object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| metadataType | MetadataType | Yes | Metadata type. |
Return value
| Type | Description |
|---|---|
| Promise<Metadata> | Promise used to return the metadata. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7600202 | Unsupported metadata. Possible causes: Unsupported metadata type. |
Example
import { image } from '@kit.ImageKit';
async function GetPictureObjMetadataProperties() {
if (pictureObj != null) {
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let pictureObjMetaData: image.Metadata = await pictureObj.getMetadata(metadataType);
if (pictureObjMetaData != null) {
console.info('get picture metadata success');
} else {
console.info('get picture metadata is failed');
}
} else {
console.info(" pictureObj is null");
}
}
marshalling13+
marshalling(sequence: rpc.MessageSequence): void
Marshals this Picture object and writes it to a MessageSequence object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sequence | rpc.MessageSequence | Yes | MessageSequence object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 62980097 | IPC error. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { rpc } from '@kit.IPCKit';
class MySequence implements rpc.Parcelable {
picture: image.Picture | null = null;
constructor(conPicture: image.Picture) {
this.picture = conPicture;
}
marshalling(messageSequence: rpc.MessageSequence) {
if(this.picture != null) {
this.picture.marshalling(messageSequence);
console.info('Marshalling success !');
return true;
} else {
console.info('Marshalling failed !');
return false;
}
}
unmarshalling(messageSequence : rpc.MessageSequence) {
this.picture = image.createPictureFromParcel(messageSequence);
this.picture.getMainPixelmap().getImageInfo().then((imageInfo : image.ImageInfo) => {
console.info('Unmarshalling to get mainPixelmap information height:' + imageInfo.size.height + ' width:' + imageInfo.size.width);
}).catch((error: BusinessError) => {
console.error('Unmarshalling failed error.code: ${error.code} ,error.message: ${error.message}');
});
return true;
}
}
async function Marshalling_UnMarshalling() {
if (pictureObj != null) {
let parcelable: MySequence = new MySequence(pictureObj);
let data: rpc.MessageSequence = rpc.MessageSequence.create();
// marshalling.
data.writeParcelable(parcelable);
let ret: MySequence = new MySequence(pictureObj);
// unmarshalling.
data.readParcelable(ret);
} else {
console.info('PictureObj is null');
}
}
release13+
release(): void
Releases this Picture object.
System capability: SystemCapability.Multimedia.Image.Core
Example
import { image } from '@kit.ImageKit';
async function Release() {
let funcName = "Release";
if (pictureObj != null) {
pictureObj.release();
if (pictureObj.getMainPixelmap() == null) {
console.info(funcName, 'Success !');
} else {
console.info(funcName, 'Failed !');
}
} else {
console.info('PictureObj is null');
}
}
PixelMap7+
Provides APIs to read or write image data and obtain image information. Before calling any API in PixelMap, you must use createPixelMap to create a PixelMap object. Currently, the maximum size of a serialized PixelMap is 128 MB. A larger size will cause a display failure. The size is calculated as follows: Width * Height * Number of bytes occupied by each pixel.
Since API version 11, PixelMap supports cross-thread calls through workers. If a PixelMap object is invoked by another thread through Worker, all APIs of the PixelMap object cannot be called in the original thread. Otherwise, error 501 is reported, indicating that the server cannot complete the request.
Before calling any API in PixelMap, you must use image.createPixelMap to create a PixelMap object.
To develop an atomic service, use ImageSoure to create a PixelMap object.
Properties
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| isEditable | boolean | Yes | No | Whether the PixelMap is editable. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| isStrideAlignment11+ | boolean | Yes | No | Whether the PixelMap uses DMA memory. |
readPixelsToBuffer7+
readPixelsToBuffer(dst: ArrayBuffer): Promise<void>
Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dst | ArrayBuffer | Yes | Buffer to which the pixels will be written. The buffer size is obtained by calling getPixelBytesNumber. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsToBuffer() {
const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
if (pixelMap != undefined) {
pixelMap.readPixelsToBuffer(readBuffer).then(() => {
console.info('Succeeded in reading image pixel data.'); // Called if the condition is met.
}).catch((error: BusinessError) => {
console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
})
}
}
readPixelsToBuffer7+
readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback<void>): void
Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dst | ArrayBuffer | Yes | Buffer to which the pixels will be written. The buffer size is obtained by calling getPixelBytesNumber. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsToBuffer() {
const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
if (pixelMap != undefined) {
pixelMap.readPixelsToBuffer(readBuffer, (error: BusinessError, res: void) => {
if(error) {
console.error(`Failed to read image pixel data. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
return;
} else {
console.info('Succeeded in reading image pixel data.'); // Called if the condition is met.
}
})
}
}
readPixelsToBufferSync12+
readPixelsToBufferSync(dst: ArrayBuffer): void
Reads the pixels of this PixelMap object based on the PixelMap's pixel format and writes the data to the buffer. This API returns the result synchronously.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dst | ArrayBuffer | Yes | Buffer to which the pixels will be written. The buffer size is obtained by calling getPixelBytesNumber. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsToBufferSync() {
const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
if (pixelMap != undefined) {
pixelMap.readPixelsToBufferSync(readBuffer);
}
}
readPixels7+
readPixels(area: PositionArea): Promise<void>
Reads the pixels in the area specified by PositionArea.region of this PixelMap object in the BGRA_8888 format and writes the data to the PositionArea.pixels buffer. This API uses a promise to return the result.
You can use a formula to calculate the size of the memory to be applied for based on PositionArea.
YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area from which the pixels will be read. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsRGBA() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
if (pixelMap != undefined) {
pixelMap.readPixels(area).then(() => {
console.info('Succeeded in reading the image data in the area.'); // Called if the condition is met.
}).catch((error: BusinessError) => {
console.error(`Failed to read the image data in the area. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
})
}
}
async function ReadPixelsYUV() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(6), // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
offset: 0,
stride: 8,
region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
};
if (pixelMap != undefined) {
pixelMap.readPixels(area).then(() => {
console.info('Succeeded in reading the image data in the area.'); // Called if the condition is met.
}).catch((error: BusinessError) => {
console.error(`Failed to read the image data in the area. code is ${error.code}, message is ${error.message}`); // Called if no condition is met.
})
}
}
readPixels7+
readPixels(area: PositionArea, callback: AsyncCallback<void>): void
Reads the pixels in the area specified by PositionArea.region of this PixelMap object in the BGRA_8888 format and writes the data to the PositionArea.pixels buffer. This API uses an asynchronous callback to return the result.
You can use a formula to calculate the size of the memory to be applied for based on PositionArea.
YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area from which the pixels will be read. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsRGBA() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
if (pixelMap != undefined) {
pixelMap.readPixels(area, (error: BusinessError) => {
if (error) {
console.error(`Failed to read pixelmap from the specified area. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in reading pixelmap from the specified area.');
}
})
}
}
async function ReadPixelsYUV() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(6), // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
offset: 0,
stride: 8,
region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
};
if (pixelMap != undefined) {
pixelMap.readPixels(area, (error: BusinessError) => {
if (error) {
console.error(`Failed to read pixelmap from the specified area. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in reading pixelmap from the specified area.');
}
})
}
}
readPixelsSync12+
readPixelsSync(area: PositionArea): void
Reads the pixels in the area specified by PositionArea.region of this PixelMap object in the BGRA_8888 format and writes the data to the PositionArea.pixels buffer. This API returns the result synchronously.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area from which the pixels will be read. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ReadPixelsSync() {
const area : image.PositionArea = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
if (pixelMap != undefined) {
pixelMap.readPixelsSync(area);
}
}
writePixels7+
writePixels(area: PositionArea): Promise<void>
Reads the pixels in the PositionArea.pixels buffer in the BGRA_8888 format and writes the data to the area specified by PositionArea.region in this PixelMap object. This API uses a promise to return the result.
You can use a formula to calculate the size of the memory to be applied for based on PositionArea.
YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area to which the pixels will be written. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WritePixelsRGBA() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
let bufferArr: Uint8Array = new Uint8Array(area.pixels);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writePixels(area).then(() => {
console.info('Succeeded in writing pixelmap into the specified area.');
}).catch((error: BusinessError) => {
console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
})
}
}
async function WritePixelsYUV() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(6), // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
offset: 0,
stride: 8,
region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
};
let bufferArr: Uint8Array = new Uint8Array(area.pixels);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writePixels(area).then(() => {
console.info('Succeeded in writing pixelmap into the specified area.');
}).catch((error: BusinessError) => {
console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
})
}
}
writePixels7+
writePixels(area: PositionArea, callback: AsyncCallback<void>): void
Reads the pixels in the PositionArea.pixels buffer in the BGRA_8888 format and writes the data to the area specified by PositionArea.region in this PixelMap object. This API uses an asynchronous callback to return the result.
You can use a formula to calculate the size of the memory to be applied for based on PositionArea.
YUV region calculation formula: region to read (region.size{width * height}) * 1.5 (1 * Y component + 0.25 * U component + 0.25 * V component)
RGBA region calculation formula: region to read (region.size{width * height}) * 4 (1 * R component + 1 * G component + 1 * B component + 1 * A component)
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area to which the pixels will be written. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WritePixelsRGBA() {
const area: image.PositionArea = { pixels: new ArrayBuffer(8), // 8 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 4.
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
let bufferArr: Uint8Array = new Uint8Array(area.pixels);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writePixels(area, (error : BusinessError) => {
if (error) {
console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in writing pixelmap into the specified area.');
}
})
}
}
async function WritePixelsYUV() {
const area: image.PositionArea = { pixels: new ArrayBuffer(6), // 6 is the size of the PixelMap buffer to create. The value is calculated as follows: height * width * 1.5.
offset: 0,
stride: 8,
region: { size: { height: 2, width: 2 }, x: 0, y: 0 }
};
let bufferArr: Uint8Array = new Uint8Array(area.pixels);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writePixels(area, (error : BusinessError) => {
if (error) {
console.error(`Failed to write pixelmap into the specified area. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info('Succeeded in writing pixelmap into the specified area.');
}
})
}
}
writePixelsSync12+
writePixelsSync(area: PositionArea): void
Reads the pixels in the PositionArea.pixels buffer in the BGRA_8888 format and writes the data to the area specified by PositionArea.region in this PixelMap object. This API returns the result synchronously.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| area | PositionArea | Yes | Area to which the pixels will be written. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WritePixelsSync() {
const area: image.PositionArea = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
};
let bufferArr: Uint8Array = new Uint8Array(area.pixels);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writePixelsSync(area);
}
}
writeBufferToPixels7+
writeBufferToPixels(src: ArrayBuffer): Promise<void>
Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | ArrayBuffer | Yes | Buffer from which the pixels are read. The buffer size is obtained by calling getPixelBytesNumber. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WriteBufferToPixels() {
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let bufferArr: Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writeBufferToPixels(color).then(() => {
console.info("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((error: BusinessError) => {
console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`);
})
}
}
writeBufferToPixels7+
writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback<void>): void
Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | ArrayBuffer | Yes | Buffer from which the pixels are read. The buffer size is obtained by calling getPixelBytesNumber. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the pixels in the buffer are successfully written to the PixelMap, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WriteBufferToPixels() {
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let bufferArr: Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writeBufferToPixels(color, (error: BusinessError) => {
if (error) {
console.error(`Failed to write data from a buffer to a PixelMap. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info("Succeeded in writing data from a buffer to a PixelMap.");
}
})
}
}
writeBufferToPixelsSync12+
writeBufferToPixelsSync(src: ArrayBuffer): void
Reads the pixels in the buffer based on the PixelMap's pixel format and writes the data to this PixelMap object. This API returns the result synchronously.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| src | ArrayBuffer | Yes | Buffer from which the pixels are read. The buffer size is obtained by calling getPixelBytesNumber. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function WriteBufferToPixelsSync() {
const color : ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let bufferArr : Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
if (pixelMap != undefined) {
pixelMap.writeBufferToPixelsSync(color);
}
}
getImageInfo7+
getImageInfo(): Promise<ImageInfo>
Obtains the image information. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<ImageInfo> | Promise used to return the image information. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function GetImageInfo() {
if (pixelMap != undefined) {
pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo != undefined) {
console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height);
}
}).catch((error: BusinessError) => {
console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
})
}
}
getImageInfo7+
getImageInfo(callback: AsyncCallback<ImageInfo>): void
Obtains the image information. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<ImageInfo> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the image information obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function GetImageInfo() {
if (pixelMap != undefined) {
pixelMap.getImageInfo((error: BusinessError, imageInfo: image.ImageInfo) => {
if (error) {
console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
return;
} else {
console.info("Succeeded in obtaining the image pixel map information."+ imageInfo.size.height);
}
})
}
}
getImageInfoSync12+
getImageInfoSync(): ImageInfo
Obtains the image information. This API returns the result synchronously.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.ImageSource
Return value
| Type | Description |
|---|---|
| ImageInfo | Image information. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function GetImageInfoSync() {
if (pixelMap != undefined) {
let imageInfo : image.ImageInfo = pixelMap.getImageInfoSync();
return imageInfo;
}
return undefined;
}
getBytesNumberPerRow7+
getBytesNumberPerRow(): number
Obtains the number of bytes per row of this image.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| number | Number of bytes per row. |
Example
let rowCount: number = pixelMap.getBytesNumberPerRow();
getPixelBytesNumber7+
getPixelBytesNumber(): number
Obtains the total number of bytes of this image.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| number | Total number of bytes. |
Example
let pixelBytesNumber: number = pixelMap.getPixelBytesNumber();
getDensity9+
getDensity():number
Obtains the pixel density of this image.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| number | Pixel density. |
Example
let getDensity: number = pixelMap.getDensity();
opacity9+
opacity(rate: number, callback: AsyncCallback<void>): void
Sets an opacity rate for this image. This API uses an asynchronous callback to return the result. It is invalid for YUV images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| rate | number | Yes | Opacity rate. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Opacity() {
let rate: number = 0.5;
if (pixelMap != undefined) {
pixelMap.opacity(rate, (err: BusinessError) => {
if (err) {
console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in setting opacity.");
}
})
}
}
opacity9+
opacity(rate: number): Promise<void>
Sets an opacity rate for this image. This API uses a promise to return the result. It is invalid for YUV images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| rate | number | Yes | Opacity rate. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Opacity() {
let rate: number = 0.5;
if (pixelMap != undefined) {
pixelMap.opacity(rate).then(() => {
console.info('Succeeded in setting opacity.');
}).catch((err: BusinessError) => {
console.error(`Failed to set opacity. code is ${err.code}, message is ${err.message}`);
})
}
}
opacitySync12+
opacitySync(rate: number): void
Sets an opacity rate for this image. This API returns the result synchronously. It is invalid for YUV images.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| rate | number | Yes | Opacity rate. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function OpacitySync() {
let rate : number = 0.5;
if (pixelMap != undefined) {
pixelMap.opacitySync(rate);
}
}
createAlphaPixelmap9+
createAlphaPixelmap(): Promise<PixelMap>
Creates a PixelMap object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses a promise to return the result. It is invalid for YUV images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreateAlphaPixelmap() {
if (pixelMap != undefined) {
pixelMap.createAlphaPixelmap().then((alphaPixelMap: image.PixelMap) => {
console.info('Succeeded in creating alpha pixelmap.');
}).catch((error: BusinessError) => {
console.error(`Failed to create alpha pixelmap. code is ${error.code}, message is ${error.message}`);
})
}
}
createAlphaPixelmap9+
createAlphaPixelmap(callback: AsyncCallback<PixelMap>): void
Creates a PixelMap object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses an asynchronous callback to return the result. It is invalid for YUV images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<PixelMap> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the PixelMap object obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreateAlphaPixelmap() {
if (pixelMap != undefined) {
pixelMap.createAlphaPixelmap((err: BusinessError, alphaPixelMap: image.PixelMap) => {
if (alphaPixelMap == undefined) {
console.error(`Failed to obtain new pixel map. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info('Succeeded in obtaining new pixel map.');
}
})
}
}
createAlphaPixelmapSync12+
createAlphaPixelmapSync(): PixelMap
Creates a PixelMap object that contains only the alpha channel information. This object can be used for the shadow effect. This API returns the result synchronously. It is invalid for YUV images.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| PixelMap | Returns a PixelMap object if the operation is successful; throws an error otherwise. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CreateAlphaPixelmapSync() {
if (pixelMap != undefined) {
let pixelmap : image.PixelMap = pixelMap.createAlphaPixelmapSync();
return pixelmap;
}
return undefined;
}
scale9+
scale(x: number, y: number, callback: AsyncCallback<void>): void
Scales this image based on the scale factors of the width and height. This API uses an asynchronous callback to return the result.
NOTE
You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | Scale factor of the width. |
| y | number | Yes | Scale factor of the height. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Scale() {
let scaleX: number = 2.0;
let scaleY: number = 1.0;
if (pixelMap != undefined) {
pixelMap.scale(scaleX, scaleY, (err: BusinessError) => {
if (err) {
console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in scaling pixelmap.");
}
})
}
}
scale9+
scale(x: number, y: number): Promise<void>
Scales this image based on the scale factors of the width and height. This API uses a promise to return the result.
NOTE
You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | Scale factor of the width. |
| y | number | Yes | Scale factor of the height. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Scale() {
let scaleX: number = 2.0;
let scaleY: number = 1.0;
if (pixelMap != undefined) {
pixelMap.scale(scaleX, scaleY).then(() => {
console.info('Succeeded in scaling pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
})
}
}
scaleSync12+
scaleSync(x: number, y: number): void
Scales this image based on the scale factors of the width and height. This API returns the result synchronously.
NOTE
You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | Scale factor of the width. |
| y | number | Yes | Scale factor of the height. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ScaleSync() {
let scaleX: number = 2.0;
let scaleY: number = 1.0;
if (pixelMap != undefined) {
pixelMap.scaleSync(scaleX, scaleY);
}
}
scale12+
scale(x: number, y: number, level: AntiAliasingLevel): Promise<void>
Scales this image based on the specified anti-aliasing level and the scale factors for the width and height. This API uses a promise to return the result.
NOTE
You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | Scale factor of the width. |
| y | number | Yes | Scale factor of the height. |
| level | AntiAliasingLevel | Yes | Anti-aliasing level. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Scale() {
let scaleX: number = 2.0;
let scaleY: number = 1.0;
if (pixelMap != undefined) {
pixelMap.scale(scaleX, scaleY, image.AntiAliasingLevel.LOW).then(() => {
console.info('Succeeded in scaling pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to scale pixelmap. code is ${err.code}, message is ${err.message}`);
})
}
}
scaleSync12+
scaleSync(x: number, y: number, level: AntiAliasingLevel): void
Scales this image based on the specified anti-aliasing level and the scale factors for the width and height. This API returns the result synchronously.
NOTE
You are advised to set the scale factors to non-negative numbers to avoid a flipping effect.
Scale factors of the width and height = Width and height of the resized image/Width and height of the original image
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | Scale factor of the width. |
| y | number | Yes | Scale factor of the height. |
| level | AntiAliasingLevel | Yes | Anti-aliasing level. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function ScaleSync() {
let scaleX: number = 2.0;
let scaleY: number = 1.0;
if (pixelMap != undefined) {
pixelMap.scaleSync(scaleX, scaleY, image.AntiAliasingLevel.LOW);
}
}
translate9+
translate(x: number, y: number, callback: AsyncCallback<void>): void
Translates this image based on given coordinates. This API uses an asynchronous callback to return the result.
The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | X coordinate to translate, in px. |
| y | number | Yes | Y coordinate to translate, in px. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Translate() {
let translateX: number = 50.0;
let translateY: number = 10.0;
if (pixelMap != undefined) {
pixelMap.translate(translateX, translateY, (err: BusinessError) => {
if (err) {
console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in translating pixelmap.");
}
})
}
}
translate9+
translate(x: number, y: number): Promise<void>
Translates this image based on given coordinates. This API uses a promise to return the result.
The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | X coordinate to translate, in px. |
| y | number | Yes | Y coordinate to translate, in px. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Translate() {
let translateX: number = 50.0;
let translateY: number = 10.0;
if (pixelMap != undefined) {
pixelMap.translate(translateX, translateY).then(() => {
console.info('Succeeded in translating pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to translate pixelmap. code is ${err.code}, message is ${err.message}`);
})
}
}
translateSync12+
translateSync(x: number, y: number): void
Translates this image based on given coordinates. This API returns the result synchronously.
The size of the translated image is changed to width+X and height+Y. It is recommended that the new width and height not exceed the width and height of the screen.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| x | number | Yes | X coordinate to translate, in px. |
| y | number | Yes | Y coordinate to translate, in px. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function TranslateSync() {
let translateX : number = 50.0;
let translateY : number = 10.0;
if (pixelMap != undefined) {
pixelMap.translateSync(translateX, translateY);
}
}
rotate9+
rotate(angle: number, callback: AsyncCallback<void>): void
Rotates this image based on a given angle. This API uses an asynchronous callback to return the result.
NOTE
The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| angle | number | Yes | Angle to rotate. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Rotate() {
let angle: number = 90.0;
if (pixelMap != undefined) {
pixelMap.rotate(angle, (err: BusinessError) => {
if (err) {
console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in rotating pixelmap.");
}
})
}
}
rotate9+
rotate(angle: number): Promise<void>
Rotates this image based on a given angle. This API uses a promise to return the result.
NOTE
The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| angle | number | Yes | Angle to rotate. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Rotate() {
let angle: number = 90.0;
if (pixelMap != undefined) {
pixelMap.rotate(angle).then(() => {
console.info('Succeeded in rotating pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to rotate pixelmap. code is ${err.code}, message is ${err.message}`);
})
}
}
rotateSync12+
rotateSync(angle: number): void
Rotates this image based on a given angle. This API returns the result synchronously.
NOTE
The allowable range for image rotation angles is between 0 and 360 degrees. Angles outside this range are automatically adjusted according to the 360-degree cycle. For example, an angle of -100 degrees will produce the same result as 260 degrees.
If the rotation angle is not an integer multiple of 90 degrees, the image size will change after rotation.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| angle | number | Yes | Angle to rotate. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function RotateSync() {
let angle : number = 90.0;
if (pixelMap != undefined) {
pixelMap.rotateSync(angle);
}
}
flip9+
flip(horizontal: boolean, vertical: boolean, callback: AsyncCallback<void>): void
Flips this image horizontally or vertically, or both. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| horizontal | boolean | Yes | Whether to flip the image horizontally. |
| vertical | boolean | Yes | Whether to flip the image vertically. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Flip() {
let horizontal: boolean = true;
let vertical: boolean = false;
if (pixelMap != undefined) {
pixelMap.flip(horizontal, vertical, (err: BusinessError) => {
if (err) {
console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in flipping pixelmap.");
}
})
}
}
flip9+
flip(horizontal: boolean, vertical: boolean): Promise<void>
Flips this image horizontally or vertically, or both. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| horizontal | boolean | Yes | Whether to flip the image horizontally. |
| vertical | boolean | Yes | Whether to flip the image vertically. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Flip() {
let horizontal: boolean = true;
let vertical: boolean = false;
if (pixelMap != undefined) {
pixelMap.flip(horizontal, vertical).then(() => {
console.info('Succeeded in flipping pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to flip pixelmap. code is ${err.code}, message is ${err.message}`);
})
}
}
flipSync12+
flipSync(horizontal: boolean, vertical: boolean): void
Flips this image horizontally or vertically, or both. This API returns the result synchronously.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| horizontal | boolean | Yes | Whether to flip the image horizontally. |
| vertical | boolean | Yes | Whether to flip the image vertically. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function FlipSync() {
let horizontal : boolean = true;
let vertical : boolean = false;
if (pixelMap != undefined) {
pixelMap.flipSync(horizontal, vertical);
}
}
crop9+
crop(region: Region, callback: AsyncCallback<void>): void
Crops this image based on a given size. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| region | Region | Yes | Size of the image after cropping. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Crop() {
let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
if (pixelMap != undefined) {
pixelMap.crop(region, (err: BusinessError) => {
if (err) {
console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info("Succeeded in cropping pixelmap.");
}
})
}
}
crop9+
crop(region: Region): Promise<void>
Crops this image based on a given size. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| region | Region | Yes | Size of the image after cropping. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Crop() {
let region: image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
if (pixelMap != undefined) {
pixelMap.crop(region).then(() => {
console.info('Succeeded in cropping pixelmap.');
}).catch((err: BusinessError) => {
console.error(`Failed to crop pixelmap. code is ${err.code}, message is ${err.message}`);
});
}
}
cropSync12+
cropSync(region: Region): void
Crops this image based on a given size. This API returns the result synchronously.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| region | Region | Yes | Size of the image after cropping. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function CropSync() {
let region : image.Region = { x: 0, y: 0, size: { height: 100, width: 100 } };
if (pixelMap != undefined) {
pixelMap.cropSync(region);
}
}
getColorSpace10+
getColorSpace(): colorSpaceManager.ColorSpaceManager
Obtains the color space of this image.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| colorSpaceManager.ColorSpaceManager | Color space obtained. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980101 | If the image data abnormal. |
| 62980103 | If the image data unsupport. |
| 62980115 | If the image parameter invalid. |
Example
async function GetColorSpace() {
if (pixelMap != undefined) {
let csm = pixelMap.getColorSpace();
}
}
setColorSpace10+
setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void
Sets the color space for this image.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| colorSpace | colorSpaceManager.ColorSpaceManager | Yes | Color space to set. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980111 | The image source data is incomplete. |
| 62980115 | If the image parameter invalid. |
Example
import { colorSpaceManager } from '@kit.ArkGraphics2D';
async function SetColorSpace() {
let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
let csm: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
if (pixelMap != undefined) {
pixelMap.setColorSpace(csm);
}
}
applyColorSpace11+
applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager, callback: AsyncCallback<void>): void
Performs color space conversion (CSC) on the image pixel color based on a given color space. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| targetColorSpace | colorSpaceManager.ColorSpaceManager | Yes | Target color space. SRGB, DCI_P3, DISPLAY_P3, and ADOBE_RGB_1998 are supported. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980104 | Failed to initialize the internal object. |
| 62980108 | Failed to convert the color space. |
| 62980115 | Invalid image parameter. |
Example
import { colorSpaceManager } from '@kit.ArkGraphics2D';
import { BusinessError } from '@kit.BasicServicesKit';
async function ApplyColorSpace() {
let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
if (pixelMap != undefined) {
pixelMap.applyColorSpace(targetColorSpace, (err: BusinessError) => {
if (err) {
console.error(`Failed to apply color space for pixelmap object. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info('Succeeded in applying color space for pixelmap object.');
}
})
}
}
applyColorSpace11+
applyColorSpace(targetColorSpace: colorSpaceManager.ColorSpaceManager): Promise<void>
Performs CSC on the image pixel color based on a given color space. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| targetColorSpace | colorSpaceManager.ColorSpaceManager | Yes | Target color space. SRGB, DCI_P3, DISPLAY_P3, and ADOBE_RGB_1998 are supported. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed |
| 62980104 | Failed to initialize the internal object. |
| 62980108 | Failed to convert the color space. |
| 62980115 | Invalid image parameter. |
Example
import { colorSpaceManager } from '@kit.ArkGraphics2D';
import { BusinessError } from '@kit.BasicServicesKit';
async function ApplyColorSpace() {
let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
let targetColorSpace: colorSpaceManager.ColorSpaceManager = colorSpaceManager.create(colorSpaceName);
if (pixelMap != undefined) {
pixelMap.applyColorSpace(targetColorSpace).then(() => {
console.info('Succeeded in applying color space for pixelmap object.');
}).catch((error: BusinessError) => {
console.error(`Failed to apply color space for pixelmap object. code is ${error.code}, message is ${error.message}`);
})
}
}
toSdr12+
toSdr(): Promise<void>
Converts an HDR image into an SDR image. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980137 | Invalid image operation. |
Example
import image from '@ohos.multimedia.image'
import resourceManager from '@ohos.resourceManager'
import { BusinessError } from '@kit.BasicServicesKit';
// 'hdr.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let img = getContext().resourceManager.getMediaContentSync($r('app.media.hdr'));
let imageSource = image.createImageSource(img.buffer.slice(0));
let decodingOptions: image.DecodingOptions = {
desiredDynamicRange: image.DecodingDynamicRange.AUTO
};
let pixelmap = imageSource.createPixelMapSync(decodingOptions);
if (pixelmap != undefined) {
console.info('Succeeded in creating pixelMap object.');
pixelmap.toSdr().then(() => {
let imageInfo = pixelmap.getImageInfoSync();
console.info("after toSdr ,imageInfo isHdr:" + imageInfo.isHdr);
}).catch((err: BusinessError) => {
console.error(`Failed to set sdr. code is ${err.code}, message is ${err.message}`);
});
} else {
console.info('Failed to create pixelMap.');
}
getMetadata12+
getMetadata(key: HdrMetadataKey): HdrMetadataValue
Obtains the value of the metadata with a given key in this PixelMap.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | HdrMetadataKey | Yes | Key of the HDR metadata. |
Return value
| Type | Description |
|---|---|
| HdrMetadataValue | Value of the metadata with the given key. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 501 | Resource unavailable. |
| 62980173 | The DMA memory does not exist. |
| 62980302 | Memory copy failed. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import image from '@ohos.multimedia.image'
// Replace 'app.media.test' with a local HDR image.
let img = getContext().resourceManager.getMediaContentSync($r('app.media.test'));
let imageSource = image.createImageSource(img.buffer.slice(0));
let decodingOptions: image.DecodingOptions = {
desiredDynamicRange: image.DecodingDynamicRange.AUTO
};
let pixelmap = imageSource.createPixelMapSync(decodingOptions);
if (pixelmap != undefined) {
console.info('Succeeded in creating pixelMap object.');
try {
let staticMetadata = pixelmap.getMetadata(image.HdrMetadataKey.HDR_STATIC_METADATA);
console.info("getmetadata:" + JSON.stringify(staticMetadata));
} catch (e) {
console.info('pixelmap create failed' + e);
}
} else {
console.info('Failed to create pixelMap.');
}
setMetadata12+
setMetadata(key: HdrMetadataKey, value: HdrMetadataValue): Promise<void>
Sets the value for the metadata with a given key in this PixelMap.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | HdrMetadataKey | Yes | Key of the HDR metadata. |
| value | HdrMetadataValue | Yes | Value of the metadata. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 501 | Resource unavailable. |
| 62980173 | The DMA memory does not exist. |
| 62980302 | Memory copy failed. |
Example
import image from '@ohos.multimedia.image'
import { BusinessError } from '@kit.BasicServicesKit';
let staticMetadata: image.HdrStaticMetadata = {
displayPrimariesX: [1.1, 1.1, 1.1],
displayPrimariesY: [1.2, 1.2, 1.2],
whitePointX: 1.1,
whitePointY: 1.2,
maxLuminance: 2.1,
minLuminance: 1.0,
maxContentLightLevel: 2.1,
maxFrameAverageLightLevel: 2.1,
}
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
pixelMap.setMetadata(image.HdrMetadataKey.HDR_STATIC_METADATA, staticMetadata).then(() => {
console.info('Succeeded in setting pixelMap metadata.');
}).catch((error: BusinessError) => {
console.error(`Failed to set the metadata.code ${error.code},message is ${error.message}`);
})
}).catch((error: BusinessError) => {
console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`);
})
setTransferDetached12+
setTransferDetached(detached: boolean): void
Sets whether to detach from the original thread when this PixelMap is transmitted across threads. This API applies to the scenario where the PixelMap needs to be released immediately.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| detached | boolean | Yes | Whether to detach from the original thread. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 501 | Resource Unavailable |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import image from '@ohos.multimedia.image';
import taskpool from '@ohos.taskpool';
@Concurrent
// Child thread method.
async function loadPixelMap(rawFileDescriptor: number): Promise<PixelMap> {
// Create an ImageSource instance.
const imageSource = image.createImageSource(rawFileDescriptor);
// Create a pixelMap.
const pixelMap = imageSource.createPixelMapSync();
// Release the ImageSource instance.
imageSource.release();
// Disconnect the reference of the original thread after the cross-thread transfer of the pixelMap is complete.
pixelMap.setTransferDetached(true);
// Return the pixelMap to the main thread.
return pixelMap;
}
@Entry
@Component
struct Demo {
@State pixelMap: PixelMap | undefined = undefined;
// Main thread method.
private loadImageFromThread(): void {
const resourceMgr = getContext(this).resourceManager;
// 'example.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
resourceMgr.getRawFd('example.jpg').then(rawFileDescriptor => {
taskpool.execute(loadPixelMap, rawFileDescriptor).then(pixelMap => {
if (pixelMap) {
this.pixelMap = pixelMap as PixelMap;
console.log('Succeeded in creating pixelMap.');
// The main thread releases the pixelMap. Because setTransferDetached has been called when the child thread returns pixelMap, the pixelMap can be released immediately.
this.pixelMap.release();
} else {
console.error('Failed to create pixelMap.');
}
});
});
}
build() {
// ...
}
}
marshalling10+
marshalling(sequence: rpc.MessageSequence): void
Marshals this PixelMap object and writes it to a MessageSequence object.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sequence | rpc.MessageSequence | Yes | MessageSequence object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980115 | Invalid image parameter. |
| 62980097 | IPC error. |
Example
import { image } from '@kit.ImageKit';
import { rpc } from '@kit.IPCKit';
class MySequence implements rpc.Parcelable {
pixel_map: image.PixelMap;
constructor(conPixelMap : image.PixelMap) {
this.pixel_map = conPixelMap;
}
marshalling(messageSequence : rpc.MessageSequence) {
this.pixel_map.marshalling(messageSequence);
console.info('marshalling');
return true;
}
unmarshalling(messageSequence : rpc.MessageSequence) {
image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel: image.PixelMap) => {
pixelParcel.unmarshalling(messageSequence).then(async (pixelMap: image.PixelMap) => {
this.pixel_map = pixelMap;
pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
})
})
});
return true;
}
}
async function Marshalling() {
const color: ArrayBuffer = new ArrayBuffer(96);
let bufferArr: Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = 0x80;
}
let opts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.BGRA_8888,
size: { height: 4, width: 6 },
alphaType: image.AlphaType.UNPREMUL
}
let pixelMap: image.PixelMap | undefined = undefined;
image.createPixelMap(color, opts).then((srcPixelMap: image.PixelMap) => {
pixelMap = srcPixelMap;
})
if (pixelMap != undefined) {
// Implement serialization.
let parcelable: MySequence = new MySequence(pixelMap);
let data: rpc.MessageSequence = rpc.MessageSequence.create();
data.writeParcelable(parcelable);
// Implement deserialization to obtain data through the RPC.
let ret: MySequence = new MySequence(pixelMap);
data.readParcelable(ret);
}
}
unmarshalling10+
unmarshalling(sequence: rpc.MessageSequence): Promise<PixelMap>
Unmarshals a MessageSequence object to obtain a PixelMap object. To create a PixelMap object in synchronous mode, use createPixelMapFromParcel.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sequence | rpc.MessageSequence | Yes | MessageSequence object that stores the PixelMap information. |
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980115 | Invalid image parameter. |
| 62980097 | IPC error. |
| 62980096 | The operation failed. |
Example
import { image } from '@kit.ImageKit';
import { rpc } from '@kit.IPCKit';
class MySequence implements rpc.Parcelable {
pixel_map: image.PixelMap;
constructor(conPixelMap: image.PixelMap) {
this.pixel_map = conPixelMap;
}
marshalling(messageSequence: rpc.MessageSequence) {
this.pixel_map.marshalling(messageSequence);
console.info('marshalling');
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence) {
image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}).then((pixelParcel : image.PixelMap) => {
pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : image.PixelMap) => {
this.pixel_map = pixelMap;
pixelMap.getImageInfo().then((imageInfo : image.ImageInfo) => {
console.info("unmarshalling information h:" + imageInfo.size.height + "w:" + imageInfo.size.width);
})
})
});
return true;
}
}
async function Unmarshalling() {
const color: ArrayBuffer = new ArrayBuffer(96);
let bufferArr: Uint8Array = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i++) {
bufferArr[i] = 0x80;
}
let opts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.BGRA_8888,
size: { height: 4, width: 6 },
alphaType: image.AlphaType.UNPREMUL
}
let pixelMap: image.PixelMap | undefined = undefined;
image.createPixelMap(color, opts).then((srcPixelMap : image.PixelMap) => {
pixelMap = srcPixelMap;
})
if (pixelMap != undefined) {
// Implement serialization.
let parcelable: MySequence = new MySequence(pixelMap);
let data : rpc.MessageSequence = rpc.MessageSequence.create();
data.writeParcelable(parcelable);
// Implement deserialization to obtain data through the RPC.
let ret : MySequence = new MySequence(pixelMap);
data.readParcelable(ret);
}
}
release7+
release():Promise<void>
Releases this PixelMap object. This API uses a promise to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the PixelMap object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Release() {
if (pixelMap != undefined) {
pixelMap.release().then(() => {
console.info('Succeeded in releasing pixelmap object.');
}).catch((error: BusinessError) => {
console.error(`Failed to release pixelmap object. code is ${error.code}, message is ${error.message}`);
})
}
}
release7+
release(callback: AsyncCallback<void>): void
Releases this PixelMap object. This API uses an asynchronous callback to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the PixelMap object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
async function Release() {
if (pixelMap != undefined) {
pixelMap.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release pixelmap object. code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info('Succeeded in releasing pixelmap object.');
}
})
}
}
convertPixelFormat12+
convertPixelFormat(targetPixelFormat: PixelMapFormat): Promise<void>
Performs a conversion between YUV and RGB formats. Currently, only conversion between NV12/NV21 and RGB888/RGBA8888/RGB565/BGRA8888/RGBAF16 and conversion between YCRCB_P010/YCBCR_P010 and RGBA1010102 are supported.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| targetPixelFormat | PixelMapFormat | Yes | Target pixel format. Currently, only conversion between NV12/NV21 and RGB888/RGBA8888/RGB565/BGRA8888/RGBAF16 and conversion between YCRCB_P010/YCBCR_P010 and RGBA1010102 are supported. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980111 | The image source data is incomplete. |
| 62980115 | Invalid input parameter. |
| 62980178 | Failed to create the pixelmap. |
| 62980274 | The conversion failed |
| 62980276 | The type to be converted is an unsupported target pixel format |
Example
import { BusinessError } from '@kit.BasicServicesKit';
if (pixelMap != undefined) {
// Set the target pixel format to NV12.
let targetPixelFormat = image.PixelMapFormat.NV12;
pixelMap.convertPixelFormat(targetPixelFormat).then(() => {
// The pixelMap is converted to the NV12 format.
console.info('PixelMapFormat convert Succeeded');
}).catch((error: BusinessError) => {
// The pixelMap fails to be converted to the NV12 format.
console.error(`PixelMapFormat convert Failed. code is ${error.code}, message is ${error.message}`);
})
}
setMemoryNameSync13+
setMemoryNameSync(name: string): void
Sets a memory name for this PixelMap.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| name | string | Yes | Memory name, which can be set only for a PixelMap with the DMA or ASHMEM memory format. The length ranges from 1 to 31 bits. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.The length of the input parameter is too long. 2.Parameter verification failed. |
| 501 | Resource unavailable. |
| 62980286 | Memory format not supported. |
Example
import { BusinessError } from '@ohos.base';
async function SetMemoryNameSync() {
if (pixelMap != undefined) {
try {
pixelMap.setMemoryNameSync("PixelMapName Test");
} catch(e) {
let error = e as BusinessError;
console.error(`setMemoryNameSync error. code is ${error.code}, message is ${error.message}`);
}
}
}
image.createImageSource
createImageSource(uri: string): ImageSource
Creates an ImageSource instance based on a given URI.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. The following formats are supported: .jpg, .png, .gif, .bmp, .webp, .dng, .heic12+ (depending on the hardware), .svg10+, and .ico11+. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
const context: Context = getContext(this);
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
const path: string = context.filesDir + "/test.jpg";
const imageSourceApi: image.ImageSource = image.createImageSource(path);
image.createImageSource9+
createImageSource(uri: string, options: SourceOptions): ImageSource
Creates an ImageSource instance based on a given URI.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. The following formats are supported: .jpg, .png, .gif, .bmp, .webp, .dng, .heic12+ (depending on the hardware), .svg10+, and .ico11+. |
| options | SourceOptions | Yes | Image properties, including the image pixel density, pixel format, and image size. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
const context: Context = getContext(this);
// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
const path: string = context.filesDir + "/test.png";
let imageSourceApi: image.ImageSource = image.createImageSource(path, sourceOptions);
image.createImageSource7+
createImageSource(fd: number): ImageSource
Creates an ImageSource instance based on a given file descriptor.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| fd | number | Yes | File descriptor. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
import { fileIo as fs } from '@kit.CoreFileKit';
const context: Context = getContext(this);
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imageSourceApi: image.ImageSource = image.createImageSource(file.fd);
image.createImageSource9+
createImageSource(fd: number, options: SourceOptions): ImageSource
Creates an ImageSource instance based on a given file descriptor.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| fd | number | Yes | File descriptor. |
| options | SourceOptions | Yes | Image properties, including the image pixel density, pixel format, and image size. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
import { fileIo as fs } from '@kit.CoreFileKit';
let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
const filePath: string = context.filesDir + "/test.jpg";
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imageSourceApi: image.ImageSource = image.createImageSource(file.fd, sourceOptions);
image.createImageSource9+
createImageSource(buf: ArrayBuffer): ImageSource
Creates an ImageSource instance based on buffers. The data passed by buf must be undecoded. Do not pass the pixel buffer data such as RBGA and YUV. If you want to create a PixelMap based on the pixel buffer data, call image.createPixelMapSync.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Array of image buffers. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
const buf: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
const imageSourceApi: image.ImageSource = image.createImageSource(buf);
image.createImageSource9+
createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource
Creates an ImageSource instance based on buffers. The data passed by buf must be undecoded. Do not pass the pixel buffer data such as RBGA and YUV. If you want to create a PixelMap based on the pixel buffer data, call image.createPixelMapSync.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Array of image buffers. |
| options | SourceOptions | Yes | Image properties, including the image pixel density, pixel format, and image size. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
const data: ArrayBuffer = new ArrayBuffer(112);
let sourceOptions: image.SourceOptions = { sourceDensity: 120 };
const imageSourceApi: image.ImageSource = image.createImageSource(data, sourceOptions);
image.createImageSource11+
createImageSource(rawfile: resourceManager.RawFileDescriptor, options?: SourceOptions): ImageSource
Creates an ImageSource instance based on the raw file descriptor of an image resource file.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| rawfile | resourceManager.RawFileDescriptor | Yes | Raw file descriptor of the image resource file. |
| options | SourceOptions | No | Image properties, including the image pixel density, pixel format, and image size. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
import { resourceManager } from '@kit.LocalizationKit';
const context: Context = getContext(this);
// Obtain a resource manager.
const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
resourceMgr.getRawFd('test.jpg').then((rawFileDescriptor: resourceManager.RawFileDescriptor) => {
const imageSourceApi: image.ImageSource = image.createImageSource(rawFileDescriptor);
}).catch((error: BusinessError) => {
console.error(`Failed to get RawFileDescriptor.code is ${error.code}, message is ${error.message}`);
})
image.CreateIncrementalSource9+
CreateIncrementalSource(buf: ArrayBuffer): ImageSource
Creates an ImageSource instance in incremental mode based on buffers. Such an instance does not support reading or writing of EXIF information.
The ImageSource instance created in incremental mode supports the following capabilities (applicable to synchronous, callback, and promise modes):
- Obtaining image information: Call getImageInfo to obtain image information by index, or call getImageInfo to directly obtain image information.
- Obtaining an image property: Call getImageProperty to obtain the value of a property with the specified index in an image.
- Obtaining image properties: Call getImageProperties to obtain the values of properties with the given names in an image.
- Updating incremental data: Call updateData to update data.
- Creating a PixelMap object: Call createPixelMap or createPixelMap to create a PixelMap based on image decoding parameters, or call createPixelMap to create a PixelMap based on default parameters.
- Releasing an ImageSource instance: Call release to release an image source.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Incremental data. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
const context: Context = getContext(this)
let imageArray = context.resourceManager.getMediaContentSync($r('app.media.startIcon')) // Obtain the image resource.
// 'app.media.startIcon' is only an example. Replace it with the actual one in use. Otherwise, the imageArray instance fails to be created, and subsequent operations cannot be performed.
let splitBuff1 = imageArray.slice(0, imageArray.byteLength / 2) // Image slice.
let splitBuff2 = imageArray.slice(imageArray.byteLength / 2)
const imageSourceIncrementalSApi: image.ImageSource = image.CreateIncrementalSource(new ArrayBuffer(imageArray.byteLength));
imageSourceIncrementalSApi.updateData(splitBuff1, false, 0, splitBuff1.byteLength).then(() => {
imageSourceIncrementalSApi.updateData(splitBuff2, true, 0, splitBuff2.byteLength).then(() => {
let pixelMap = imageSourceIncrementalSApi.createPixelMapSync()
let imageInfo = pixelMap.getImageInfoSync()
console.info('Succeeded in creating pixelMap')
}).catch((error : BusinessError) => {
console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`)
})
}).catch((error : BusinessError) => {
console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`)
})
image.CreateIncrementalSource9+
CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
Creates an ImageSource instance in incremental mode based on buffers. Such an instance does not support reading or writing of EXIF information.
The capabilities supported by the ImageSource instance created by this API are the same as those supported by the instance created by CreateIncrementalSource(buf: ArrayBuffer): ImageSource.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Incremental data. |
| options | SourceOptions | No | Image properties, including the image pixel density, pixel format, and image size. |
Return value
| Type | Description |
|---|---|
| ImageSource | Returns the ImageSource instance if the operation is successful; returns undefined otherwise. |
Example
const context: Context = getContext(this)
let imageArray = context.resourceManager.getMediaContentSync($r('app.media.startIcon')) // Obtain the image resource.
// 'app.media.startIcon' is only an example. Replace it with the actual one in use. Otherwise, the imageArray instance fails to be created, and subsequent operations cannot be performed.
let splitBuff1 = imageArray.slice(0, imageArray.byteLength / 2) // Image slice.
let splitBuff2 = imageArray.slice(imageArray.byteLength / 2)
let sourceOptions: image.SourceOptions = { sourceDensity: 120};
const imageSourceIncrementalSApi: image.ImageSource = image.CreateIncrementalSource(new ArrayBuffer(imageArray.byteLength), sourceOptions);
imageSourceIncrementalSApi.updateData(splitBuff1, false, 0, splitBuff1.byteLength).then(() => {
imageSourceIncrementalSApi.updateData(splitBuff2, true, 0, splitBuff2.byteLength).then(() => {
let pixelMap = imageSourceIncrementalSApi.createPixelMapSync()
let imageInfo = pixelMap.getImageInfoSync()
console.info('Succeeded in creating pixelMap')
}).catch((error : BusinessError) => {
console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`)
})
}).catch((error : BusinessError) => {
console.error(`Failed to updateData error code is ${error.code}, message is ${error.message}`)
})
ImageSource
Provides APIs to obtain image information. Before calling any API in ImageSource, you must use createImageSource to create an ImageSource instance.
Properties
System capability: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| supportedFormats | Array<string> | Yes | No | Supported formats, including .png, .jpeg, .bmp, .gif, .webp, .dng., and .heic12+ (depending on the hardware). |
getImageInfo
getImageInfo(index: number, callback: AsyncCallback<ImageInfo>): void
Obtains information about an image with the specified index. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| index | number | Yes | Index of the image. |
| callback | AsyncCallback<ImageInfo> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the image information obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getImageInfo(0, (error: BusinessError, imageInfo: image.ImageInfo) => {
if (error) {
console.error(`Failed to obtain the image information.code is ${error.code}, message is ${error.message}`);
} else {
console.info('Succeeded in obtaining the image information.');
}
})
getImageInfo
getImageInfo(callback: AsyncCallback<ImageInfo>): void
Obtains information about this image. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<ImageInfo> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the image information obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getImageInfo((err: BusinessError, imageInfo: image.ImageInfo) => {
if (err) {
console.error(`Failed to obtain the image information.code is ${err.code}, message is ${err.message}`);
} else {
console.info('Succeeded in obtaining the image information.');
}
})
getImageInfo
getImageInfo(index?: number): Promise<ImageInfo>
Obtains information about an image with the specified index. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| index | number | No | Index of the image. If this parameter is not set, the default value 0 is used. |
Return value
| Type | Description |
|---|---|
| Promise<ImageInfo> | Promise used to return the image information. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getImageInfo(0)
.then((imageInfo: image.ImageInfo) => {
console.info('Succeeded in obtaining the image information.');
}).catch((error: BusinessError) => {
console.error(`Failed to obtain the image information.code is ${error.code}, message is ${error.message}`);
})
getImageInfoSync12+
getImageInfoSync(index?: number): ImageInfo
Obtains information about an image with the specified index. This API returns the result synchronously.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| index | number | No | Index of the image. If this parameter is not set, the default value 0 is used. |
Return value
| Type | Description |
|---|---|
| ImageInfo | Image information. |
Example
import { image } from '@kit.ImageKit';
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
let imageSource = image.createImageSource(filePath);
let imageInfo = imageSource.getImageInfoSync(0);
if (imageInfo == undefined) {
console.error('Failed to obtain the image information.');
} else {
console.info('Succeeded in obtaining the image information.');
console.info('imageInfo.size.height:' + imageInfo.size.height);
console.info('imageInfo.size.width:' + imageInfo.size.width);
}
getImageProperty11+
getImageProperty(key:PropertyKey, options?: ImagePropertyOptions): Promise<string>
Obtains the value of a property with the specified index in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | PropertyKey | Yes | Name of the property. |
| options | ImagePropertyOptions | No | Image properties, including the image index and default property value. |
Return value
| Type | Description |
|---|---|
| Promise<string> | Promise used to return the property value. If the operation fails, the default value is returned. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
| 62980096 | The operation failed. |
| 62980103 | The image data is not supported. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980123 | Images in EXIF format are not supported. |
| 62980135 | The EXIF value is invalid. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
let options: image.ImagePropertyOptions = { index: 0, defaultValue: '9999' }
imageSourceApi.getImageProperty(image.PropertyKey.BITS_PER_SAMPLE, options)
.then((data: string) => {
console.info('Succeeded in getting the value of the specified attribute key of the image.');
}).catch((error: BusinessError) => {
console.error('Failed to get the value of the specified attribute key of the image.');
})
getImageProperty(deprecated)
getImageProperty(key:string, options?: GetImagePropertyOptions): Promise<string>
Obtains the value of a property with the specified index in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
This API is deprecated since API version 11. You are advised to use getImageProperty.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Name of the property. |
| options | GetImagePropertyOptions | No | Image properties, including the image index and default property value. |
Return value
| Type | Description |
|---|---|
| Promise<string> | Promise used to return the property value. If the operation fails, the default value is returned. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getImageProperty("BitsPerSample")
.then((data: string) => {
console.info('Succeeded in getting the value of the specified attribute key of the image.');
}).catch((error: BusinessError) => {
console.error('Failed to get the value of the specified attribute key of the image.');
})
getImageProperty(deprecated)
getImageProperty(key:string, callback: AsyncCallback<string>): void
Obtains the value of a property with the specified index in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
This API is deprecated since API version 11. You are advised to use getImageProperty.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Name of the property. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the property value obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getImageProperty("BitsPerSample", (error: BusinessError, data: string) => {
if (error) {
console.error('Failed to get the value of the specified attribute key of the image.');
} else {
console.info('Succeeded in getting the value of the specified attribute key of the image.');
}
})
getImageProperty(deprecated)
getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCallback<string>): void
Obtains the value of a property in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
This API is deprecated since API version 11. You are advised to use getImageProperty.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Name of the property. |
| options | GetImagePropertyOptions | Yes | Image properties, including the image index and default property value. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the property value obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
let property: image.GetImagePropertyOptions = { index: 0, defaultValue: '9999' }
imageSourceApi.getImageProperty("BitsPerSample", property, (error: BusinessError, data: string) => {
if (error) {
console.error('Failed to get the value of the specified attribute key of the image.');
} else {
console.info('Succeeded in getting the value of the specified attribute key of the image.');
}
})
getImageProperties12+
getImageProperties(key: Array<PropertyKey>): Promise<Record<PropertyKey, string|null>>
Obtains the values of properties with the given names in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | Array<PropertyKey> | Yes | Array of properties names. |
Return value
| Type | Description |
|---|---|
| Promise<Record<PropertyKey, string | null>> | Promise used to return the property values. If the operation fails, null is returned. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
| 62980096 | The operation failed. |
| 62980110 | The image source data is incorrect. |
| 62980113 | Unknown image format. |
| 62980116 | Failed to decode the image. |
Example
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
let key = [image.PropertyKey.IMAGE_WIDTH, image.PropertyKey.IMAGE_LENGTH];
imageSourceApi.getImageProperties(key).then((data) => {
console.info(JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(JSON.stringify(err));
});
modifyImageProperty11+
modifyImageProperty(key: PropertyKey, value: string): Promise<void>
Modifies the value of a property in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
The property byte length is changed when the modifyImageProperty API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | PropertyKey | Yes | Name of the property. |
| value | string | Yes | New value of the property. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types; |
| 62980123 | The image does not support EXIF decoding. |
| 62980133 | The EXIF data is out of range. |
| 62980135 | The EXIF value is invalid. |
| 62980146 | The EXIF data failed to be written to the file. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.modifyImageProperty(image.PropertyKey.IMAGE_WIDTH, "120").then(() => {
imageSourceApi.getImageProperty(image.PropertyKey.IMAGE_WIDTH).then((width: string) => {
console.info(`ImageWidth is :${width}`);
}).catch((error: BusinessError) => {
console.error('Failed to get the Image Width.');
})
}).catch((error: BusinessError) => {
console.error('Failed to modify the Image Width');
})
modifyImageProperty(deprecated)
modifyImageProperty(key: string, value: string): Promise<void>
Modifies the value of a property in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
The property byte length is changed when the modifyImageProperty API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
This API is deprecated since API version 11. You are advised to use modifyImageProperty.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Name of the property. |
| value | string | Yes | New value of the property. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => {
imageSourceApi.getImageProperty("ImageWidth").then((width: string) => {
console.info(`ImageWidth is :${width}`);
}).catch((error: BusinessError) => {
console.error('Failed to get the Image Width.');
})
}).catch((error: BusinessError) => {
console.error('Failed to modify the Image Width');
})
modifyImageProperty(deprecated)
modifyImageProperty(key: string, value: string, callback: AsyncCallback<void>): void
Modifies the value of a property in this image. This API uses an asynchronous callback to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
The property byte length is changed when the modifyImageProperty API is called to modify the value of a property. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
This API is deprecated since API version 11. You are advised to use modifyImageProperty.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Name of the property. |
| value | string | Yes | New value of the property. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.modifyImageProperty("ImageWidth", "120", (err: BusinessError) => {
if (err) {
console.error(`Failed to modify the Image Width.code is ${err.code}, message is ${err.message}`);
} else {
console.info('Succeeded in modifying the Image Width.');
}
})
modifyImageProperties12+
modifyImageProperties(records: Record<PropertyKey, string|null>): Promise<void>
Modifies the values of properties in this image. This API uses a promise to return the result. This API applies only to images that are in JPEG, PNG, or HEIF12+ (depending on the hardware) format and contain the EXIF information. You can use the supportedFormats property to check whether the EXIF read/write operation for images in HEIF format is supported.
NOTE
The property byte length is changed when the modifyImageProperties API is called to modify the values of properties. Currently, you can call the API in an ImageSource instance created based on a file descriptor or path, but not an ImageSource instance created based on buffers.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| records | Record<PropertyKey, string | null> | Yes | Array of property names and property values. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
| 62980123 | The image does not support EXIF decoding. |
| 62980133 | The EXIF data is out of range. |
| 62980135 | The EXIF value is invalid. |
| 62980146 | The EXIF data failed to be written to the file. |
Example
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
let keyValues: Record<PropertyKey, string|null> = {
[image.PropertyKey.IMAGE_WIDTH] : "1024",
[image.PropertyKey.IMAGE_LENGTH] : "1024"
};
let checkKey = [image.PropertyKey.IMAGE_WIDTH, image.PropertyKey.IMAGE_LENGTH];
imageSourceApi.modifyImageProperties(keyValues).then(() => {
imageSourceApi.getImageProperties(checkKey).then((data) => {
console.info(JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(JSON.stringify(err));
});
}).catch((err: BusinessError) => {
console.error(JSON.stringify(err));
});
updateData9+
updateData(buf: ArrayBuffer, isFinished: boolean, offset: number, length: number): Promise<void>
Updates incremental data. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Incremental data. |
| isFinished | boolean | Yes | Whether the update is complete. |
| offset | number | Yes | Offset for data reading. |
| length | number | Yes | Array length. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const array: ArrayBuffer = new ArrayBuffer(100);
imageSourceApi.updateData(array, false, 0, 10).then(() => {
console.info('Succeeded in updating data.');
}).catch((err: BusinessError) => {
console.error(`Failed to update data.code is ${err.code},message is ${err.message}`);
})
updateData9+
updateData(buf: ArrayBuffer, isFinished: boolean, offset: number, length: number, callback: AsyncCallback<void>): void
Updates incremental data. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buf | ArrayBuffer | Yes | Incremental data. |
| isFinished | boolean | Yes | Whether the update is complete. |
| offset | number | Yes | Offset for data reading. |
| length | number | Yes | Array length. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const array: ArrayBuffer = new ArrayBuffer(100);
imageSourceApi.updateData(array, false, 0, 10, (err: BusinessError) => {
if (err) {
console.error(`Failed to update data.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in updating data.');
}
})
createPicture13+
createPicture(options?: DecodingOptionsForPicture): Promise<Picture>
Creates a Picture object based on image decoding parameters. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptionsForPicture | No | Image decoding parameters. |
Return value
| Type | Description |
|---|---|
| Promise<Picture> | Promise used to return the Picture object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes: 1.Mandatory parameters are left unspecified.2.Incorrect parameter types; 3.Parameter verification failed. |
| 7700301 | Decode failed. |
Example
import { image } from '@kit.ImageKit';
async function CreatePicture() {
let options: image.DecodingOptionsForPicture = {
desiredAuxiliaryPictures: [image.AuxiliaryPictureType.GAINMAP] // GAINMAP indicates the type of the auxiliary picture to be decoded.
};
let pictureObj: image.Picture = await imageSourceApi.createPicture(options);
if (pictureObj != null) {
console.info('Create picture succeeded');
} else {
console.info('Create picture failed');
}
}
createPixelMap7+
createPixelMap(options?: DecodingOptions): Promise<PixelMap>
Creates a PixelMap object based on image decoding parameters. This API uses a promise to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptions | No | Image decoding parameters. |
Return value
| Type | Description |
|---|---|
| Promise<PixelMap> | Promise used to return the PixelMap object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.createPixelMap().then((pixelMap: image.PixelMap) => {
console.info('Succeeded in creating pixelMap object through image decoding parameters.');
}).catch((error: BusinessError) => {
console.error('Failed to create pixelMap object through image decoding parameters.');
})
createPixelMap7+
createPixelMap(callback: AsyncCallback<PixelMap>): void
Creates a PixelMap object based on the default parameters. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<PixelMap> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the PixelMap object obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.createPixelMap((err: BusinessError, pixelMap: image.PixelMap) => {
if (err) {
console.error(`Failed to create pixelMap.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in creating pixelMap object.');
}
})
createPixelMap7+
createPixelMap(options: DecodingOptions, callback: AsyncCallback<PixelMap>): void
Creates a PixelMap object based on image decoding parameters. This API uses an asynchronous callback to return the result.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptions | Yes | Image decoding parameters. |
| callback | AsyncCallback<PixelMap> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the PixelMap object obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
let decodingOptions: image.DecodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 1, height: 2 },
rotate: 10,
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 },
index: 0
};
imageSourceApi.createPixelMap(decodingOptions, (err: BusinessError, pixelMap: image.PixelMap) => {
if (err) {
console.error(`Failed to create pixelMap.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in creating pixelMap object.');
}
})
createPixelMapSync12+
createPixelMapSync(options?: DecodingOptions): PixelMap
Creates a PixelMap object based on image decoding parameters. This API returns the result synchronously.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptions | No | Image decoding parameters. |
Return value
| Type | Description |
|---|---|
| PixelMap | PixelMap object. |
Example
import { image } from '@kit.ImageKit';
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
let imageSource = image.createImageSource(filePath);
let decodingOptions: image.DecodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 1, height: 2 },
rotate: 10,
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 },
index: 0
};
let pixelmap = imageSource.createPixelMapSync(decodingOptions);
if (pixelmap != undefined) {
console.info('Succeeded in creating pixelMap object.');
} else {
console.info('Failed to create pixelMap.');
}
createPixelMapList10+
createPixelMapList(options?: DecodingOptions): Promise<Array<PixelMap>>
Creates an array of PixelMap objects based on image decoding parameters. This API uses a promise to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
NOTE
This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the Image component for displaying animations. The Image component decodes frames one by one, which uses less memory than this function.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptions | No | Image decoding parameters. |
Return value
| Type | Description |
|---|---|
| Promise<Array<PixelMap>> | Promise used to return an array of PixelMap objects. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980099 | The shared memory data is abnormal. |
| 62980101 | The image data is abnormal. |
| 62980103 | The image data is not supported. |
| 62980106 | The image is too large. |
| 62980109 | Failed to crop the image. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
| 62980173 | The DMA memory does not exist. |
| 62980174 | The DMA memory data is abnormal. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
let decodeOpts: image.DecodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 198, height: 202 },
rotate: 0,
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
index: 0,
};
imageSourceApi.createPixelMapList(decodeOpts).then((pixelMapList: Array<image.PixelMap>) => {
console.info('Succeeded in creating pixelMapList object.');
}).catch((err: BusinessError) => {
console.error(`Failed to create pixelMapList object.code is ${err.code},message is ${err.message}`);
})
createPixelMapList10+
createPixelMapList(callback: AsyncCallback<Array<PixelMap>>): void
Creates an array of PixelMap objects based on the default parameters. This API uses an asynchronous callback to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
NOTE
This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the Image component for displaying animations. The Image component decodes frames one by one, which uses less memory than this function.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Array<PixelMap>> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the array of PixelMap objects obtained; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980099 | The shared memory data is abnormal. |
| 62980101 | The image data is abnormal. |
| 62980103 | The image data is not supported. |
| 62980106 | The image is too large. |
| 62980109 | Failed to crop the image. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
| 62980173 | The DMA memory does not exist. |
| 62980174 | The DMA memory data is abnormal. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.createPixelMapList((err: BusinessError, pixelMapList: Array<image.PixelMap>) => {
if (err) {
console.error(`Failed to create pixelMapList object.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in creating pixelMapList object.');
}
})
createPixelMapList10+
createPixelMapList(options: DecodingOptions, callback: AsyncCallback<Array<PixelMap>>): void
Creates an array of PixelMap objects based on image decoding parameters. This API uses an asynchronous callback to return the result. For dynamic images such as GIF and WebP images, this API returns the data of each frame of the image. For static images, this API returns the data of the unique frame of the image.
NOTE
This function decodes all frames at once. If the number of frames is high or the size of individual frames is large, it can lead to significant memory usage. In these cases, you are advised to use the Image component for displaying animations. The Image component decodes frames one by one, which uses less memory than this function.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | DecodingOptions | Yes | Image decoding parameters. |
| callback | AsyncCallback<Array<PixelMap>> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the array of PixelMap objects obtained; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980099 | The shared memory data is abnormal. |
| 62980101 | The image data is abnormal. |
| 62980103 | The image data is not supported. |
| 62980106 | The image is too large. |
| 62980109 | Failed to crop the image. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
| 62980173 | The DMA memory does not exist. |
| 62980174 | The DMA memory data is abnormal. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
let decodeOpts: image.DecodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 198, height: 202 },
rotate: 0,
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
index: 0,
};
imageSourceApi.createPixelMapList(decodeOpts, (err: BusinessError, pixelMapList: Array<image.PixelMap>) => {
if (err) {
console.error(`Failed to create pixelMapList object.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in creating pixelMapList object.');
}
})
getDelayTimeList10+
getDelayTimeList(callback: AsyncCallback<Array<number>>): void
Obtains an array of delay times. This API uses an asynchronous callback to return the result. This API applies only to images in GIF or WebP format.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the array of delay times obtained; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
| 62980149 | Invalid MIME type for the image source. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getDelayTimeList((err: BusinessError, delayTimes: Array<number>) => {
if (err) {
console.error(`Failed to get delayTimes object.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in getting delayTimes object.');
}
})
getDelayTimeList10+
getDelayTimeList(): Promise<Array<number>>
Obtains an array of delay times. This API uses a promise to return the result. This API applies only to images in GIF or WebP format.
System capability: SystemCapability.Multimedia.Image.ImageSource
Return value
| Type | Description |
|---|---|
| Promise<Array<number>> | Promise used to return an array of delay times. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
| 62980149 | Invalid MIME type for the image source. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getDelayTimeList().then((delayTimes: Array<number>) => {
console.info('Succeeded in getting delayTimes object.');
}).catch((err: BusinessError) => {
console.error(`Failed to get delayTimes object.code is ${err.code},message is ${err.message}`);
})
getFrameCount10+
getFrameCount(callback: AsyncCallback<number>): void
Obtains the number of frames. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the number of frames obtained; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getFrameCount((err: BusinessError, frameCount: number) => {
if (err) {
console.error(`Failed to get frame count.code is ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in getting frame count.');
}
})
getFrameCount10+
getFrameCount(): Promise<number>
Obtains the number of frames. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageSource
Return value
| Type | Description |
|---|---|
| Promise<number> | Promise used to return the number of frames. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980110 | The image source data is incorrect. |
| 62980111 | The image source data is incomplete. |
| 62980112 | The image format does not match. |
| 62980113 | Unknown image format. |
| 62980115 | Invalid image parameter. |
| 62980116 | Failed to decode the image. |
| 62980118 | Failed to create the image plugin. |
| 62980122 | Failed to decode the image header. |
| 62980137 | Invalid media operation. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getFrameCount().then((frameCount: number) => {
console.info('Succeeded in getting frame count.');
}).catch((err: BusinessError) => {
console.error(`Failed to get frame count.code is ${err.code},message is ${err.message}`);
})
getDisposalTypeList12+
getDisposalTypeList(): Promise<Array<number>>
Obtains the list of disposal types. This API uses a promise to return the result. It is used only for GIF images.
System capability: SystemCapability.Multimedia.Image.ImageSource
Return value
| Type | Description |
|---|---|
| Promise<Array<number>> | Promise used to return an array of disposal types. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The operation failed. |
| 62980101 | The image data is abnormal. |
| 62980137 | Invalid media operation. |
| 62980149 | Invalid MIME type for the image source. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.getDisposalTypeList().then((disposalTypes: Array<number>) => {
console.info('Succeeded in getting disposalTypes object.');
}).catch((err: BusinessError) => {
console.error(`Failed to get disposalTypes object.code ${err.code},message is ${err.message}`);
})
release
release(callback: AsyncCallback<void>): void
Releases this ImageSource instance. This API uses an asynchronous callback to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageSource object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageSource
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release the image source instance.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing the image source instance.');
}
})
release
release(): Promise<void>
Releases this ImageSource instance. This API uses a promise to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageSource object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageSource
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imageSourceApi.release().then(() => {
console.info('Succeeded in releasing the image source instance.');
}).catch((error: BusinessError) => {
console.error(`Failed to release the image source instance.code ${error.code},message is ${error.message}`);
})
image.createImagePacker
createImagePacker(): ImagePacker
Creates an ImagePacker instance.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Return value
| Type | Description |
|---|---|
| ImagePacker | ImagePacker instance created. |
Example
const imagePackerApi: image.ImagePacker = image.createImagePacker();
ImagePacker
Provides APIs to pack images. Before calling any API in ImagePacker, you must use createImagePacker to create an ImagePacker object. Currently, this class applies only to images in .jpeg, .webp, .png, or heif12+ (depending on the hardware).
Properties
System capability: SystemCapability.Multimedia.Image.ImagePacker
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| supportedFormats | Array<string> | Yes | No | Supported formats, including .jpeg, .webp, .png, and heic12+ (depending on the hardware). |
packToData13+
packToData(source: ImageSource, options: PackingOption): Promise<ArrayBuffer>
Packs an image. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | ImageSource | Yes | Image to pack. |
| options | PackingOption | Yes | Option for image packing. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the parameter is invalid. |
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the packed image data. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packToData(imageSourceApi, packOpts)
.then((data: ArrayBuffer) => {
console.info('Succeeded in packing the image.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
})
packToData13+
packToData(source: PixelMap, options: PackingOption): Promise<ArrayBuffer>
Packs an image. This API uses a promise to return the result.
NOTE
If error code 401 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | PixelMap | Yes | PixelMap object to pack. |
| options | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the packed image data. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the parameter is invalid. |
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packToData(pixelMap, packOpts)
.then((data: ArrayBuffer) => {
console.info('Succeeded in packing the image.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
})
}).catch((error: BusinessError) => {
console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
})
packing13+
packing(picture: Picture, options: PackingOption): Promise<ArrayBuffer>
Packs a picture. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| picture | Picture | Yes | Picture object to pack. |
| options | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the packed image data. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7800301 | Encode failed. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function Packing() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("test.jpg");
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let funcName = "Packing";
if (imagePackerApi != null) {
let opts: image.PackingOption = {
format: "image/jpeg",
quality: 98,
bufferSize: 10,
desiredDynamicRange: image.PackingDynamicRange.AUTO,
needsPackProperties: true};
await imagePackerApi.packing(pictureObj, opts).then((data: ArrayBuffer) => {
console.info(funcName, 'Succeeded in packing the image.'+ data);
}).catch((error: BusinessError) => {
console.error(funcName, 'Failed to pack the image.code ${error.code},message is ${error.message}');
});
}
}
packing(deprecated)
packing(source: ImageSource, option: PackingOption, callback: AsyncCallback<ArrayBuffer>): void
Packs an image. This API uses an asynchronous callback to return the result.
NOTE
This API is supported since API version 6 and deprecated since API version 13. Use packToData instead.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | ImageSource | Yes | Image to pack. |
| option | PackingOption | Yes | Option for image packing. |
| callback | AsyncCallback<ArrayBuffer> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the packed image data; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in packing the image.');
}
})
packing(deprecated)
packing(source: ImageSource, option: PackingOption): Promise<ArrayBuffer>
Packs an image. This API uses a promise to return the result.
NOTE
This API is supported since API version 6 and deprecated since API version 13. Use packToData instead.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | ImageSource | Yes | Image to pack. |
| option | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the packed image data. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const context: Context = getContext();
// 'test.jpg' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
let filePath: string = context.filesDir + "/test.jpg";
const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packing(imageSourceApi, packOpts)
.then((data: ArrayBuffer) => {
console.info('Succeeded in packing the image.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
})
packing(deprecated)
packing(source: PixelMap, option: PackingOption, callback: AsyncCallback<ArrayBuffer>): void
Packs an image. This API uses an asynchronous callback to return the result.
NOTE
This API is supported since API version 8 and deprecated since API version 13. Use packToData instead.
NOTE If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | PixelMap | Yes | PixelMap object to pack. |
| option | PackingOption | Yes | Option for image packing. |
| callback | AsyncCallback<ArrayBuffer> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the packed image data; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`Failed to pack the image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in packing the image.');
}
})
}).catch((error: BusinessError) => {
console.error(`Failed to create the PixelMap.code ${error.code},message is ${error.message}`);
})
packing(deprecated)
packing(source: PixelMap, option: PackingOption): Promise<ArrayBuffer>
Packs an image. This API uses a promise to return the result.
NOTE
This API is supported since API version 8 and deprecated since API version 13. Use packToData instead.
If the message "PixelMap mismatch" is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | PixelMap | Yes | PixelMap object to pack. |
| option | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the packed image data. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packing(pixelMap, packOpts)
.then((data: ArrayBuffer) => {
console.info('Succeeded in packing the image.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
})
}).catch((error: BusinessError) => {
console.error(`Failed to create PixelMap.code ${error.code},message is ${error.message}`);
})
release
release(callback: AsyncCallback<void>): void
Releases this ImagePacker instance. This API uses an asynchronous callback to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imagePackerApi.release((err: BusinessError)=>{
if (err) {
console.error(`Failed to release image packaging.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing image packaging.');
}
})
release
release(): Promise<void>
Releases this ImagePacker instance. This API uses a promise to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImagePacker object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
imagePackerApi.release().then(() => {
console.info('Succeeded in releasing image packaging.');
}).catch((error: BusinessError) => {
console.error(`Failed to release image packaging.code ${error.code},message is ${error.message}`);
})
packToFile11+
packToFile(source: ImageSource, fd: number, options: PackingOption, callback: AsyncCallback<void>): void
Encodes an ImageSource object and packs it into a file. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | ImageSource | Yes | Image to pack. |
| fd | number | Yes | File descriptor. |
| options | PackingOption | Yes | Option for image packing. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980115 | If the parameter is invalid. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';
const context: Context = getContext(this);
// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
const path: string = context.filesDir + "/test.png";
const imageSourceApi: image.ImageSource = image.createImageSource(path);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
const filePath: string = context.filesDir + "/image_source.jpg";
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts, (err: BusinessError) => {
if (err) {
console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in packing the image to file.');
}
})
packToFile11+
packToFile (source: ImageSource, fd: number, options: PackingOption): Promise<void>
Encodes an ImageSource object and packs it into a file. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | ImageSource | Yes | Image to pack. |
| fd | number | Yes | File descriptor. |
| options | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980115 | If the parameter is invalid. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';
const context: Context = getContext(this);
// 'test.png' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed.
const path: string = context.filesDir + "/test.png";
const imageSourceApi: image.ImageSource = image.createImageSource(path);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
const filePath: string = context.filesDir + "/image_source.jpg";
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts).then(() => {
console.info('Succeeded in packing the image to file.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
})
packToFile11+
packToFile (source: PixelMap, fd: number, options: PackingOption, callback: AsyncCallback<void>): void;
Encodes a PixelMap object and packs it into a file. This API uses an asynchronous callback to return the result.
NOTE
If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | PixelMap | Yes | PixelMap object to pack. |
| fd | number | Yes | File descriptor. |
| options | PackingOption | Yes | Option for image packing. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980115 | If the parameter is invalid. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
const context: Context = getContext(this);
const path: string = context.filesDir + "/pixel_map.jpg";
image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packToFile(pixelmap, file.fd, packOpts, (err: BusinessError) => {
if (err) {
console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in packing the image to file.');
}
})
})
packToFile11+
packToFile (source: PixelMap, fd: number, options: PackingOption): Promise<void>
Encodes a PixelMap object and packs it into a file. This API uses a promise to return the result.
NOTE
If error code 62980115 is returned, the parameters are abnormal. The possible cause is that the PixelMap object is released in advance. You need to check the code and ensure that the PixelMap object is released after this API is called.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| source | PixelMap | Yes | PixelMap object to pack. |
| fd | number | Yes | File descriptor. |
| options | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 62980096 | The Operation failed. |
| 62980101 | The image data is abnormal. |
| 62980106 | The image is too large. |
| 62980113 | Unknown image format. |
| 62980115 | If the parameter is invalid. |
| 62980119 | If encoder occur error during encoding. |
| 62980120 | Add pixelmap out of range. |
| 62980172 | Failed to encode icc. |
| 62980252 | Failed to create surface. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';
const color: ArrayBuffer = new ArrayBuffer(96); // 96 is the size of the pixel buffer to create. The value is calculated as follows: height * width *4.
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 4, width: 6 } }
const context: Context = getContext(this);
const path: string = context.filesDir + "/pixel_map.jpg";
image.createPixelMap(color, opts).then((pixelmap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packToFile(pixelmap, file.fd, packOpts)
.then(() => {
console.info('Succeeded in packing the image to file.');
}).catch((error: BusinessError) => {
console.error(`Failed to pack the image to file.code ${error.code},message is ${error.message}`);
})
})
packToFile13+
packToFile(picture: Picture, fd: number, options: PackingOption): Promise<void>
Encodes a Picture object and packs it into a file. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImagePacker
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| picture | Picture | Yes | Picture object to pack. |
| fd | number | Yes | File descriptor. |
| options | PackingOption | Yes | Option for image packing. |
Return value
| Type | Description |
|---|---|
| Promise<void> | that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7800301 | Encode failed. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
async function PackToFile() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("test.jpg");
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let funcName = "PackToFile";
if (imagePackerApi != null) {
const context: Context = getContext();
const filePath: string = context.filesDir + "/test.jpg";
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let packOpts: image.PackingOption = {
format: "image/jpeg",
quality: 98,
bufferSize: 10,
desiredDynamicRange: image.PackingDynamicRange.AUTO,
needsPackProperties: true};
await imagePackerApi.packToFile(pictureObj, file.fd, packOpts).then(() => {
console.info(funcName, 'Succeeded in packing the image to file.');
}).catch((error: BusinessError) => {
console.error(funcName, 'Failed to pack the image to file.code ${error.code},message is ${error.message}');
});
}
}
image.createAuxiliaryPicture13+
createAuxiliaryPicture(buffer: ArrayBuffer, size: Size, type: AuxiliaryPictureType): AuxiliaryPicture
Creates an AuxiliaryPicture instance based on the ArrayBuffer image data, auxiliary picture size, and auxiliary picture type.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Image data stored in the buffer. |
| size | Size | Yes | Size of the auxiliary picture. |
| type | AuxiliaryPictureType | Yes | Type of the auxiliary picture. |
Return value
| Type | Description |
|---|---|
| AuxiliaryPicture | AuxiliaryPicture instance if the operation is successful. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
Example
import { image } from '@kit.ImageKit';
async function CreateAuxiliaryPicture() {
let funcName = "CreateAuxiliaryPicture";
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
let auxBuffer: ArrayBuffer = rawFile.buffer as ArrayBuffer;
let auxSize: Size = {
height: 180,
width: 240
};
let auxType: image.AuxiliaryPictureType = image.AuxiliaryPictureType.GAINMAP;
let auxPictureObj: image.AuxiliaryPicture | null = image.createAuxiliaryPicture(auxBuffer, auxSize, auxType);
if(auxPictureObj != null) {
let type: image.AuxiliaryPictureType = auxPictureObj.getType();
console.info(funcName, 'CreateAuxiliaryPicture succeeded this.Aux_picture.type.' + JSON.stringify(type));
} else {
console.error(funcName, 'CreateAuxiliaryPicture failed');
}
}
AuxiliaryPicture13+
The auxiliary picture is generally used to assist the main picture in displaying special information, so that the image includes richer information. The AuxiliaryPicture class is used to read or write auxiliary picture data of an image and obtain auxiliary picture information of an image. Before calling any API in AuxiliaryPicture, you must use createAuxiliaryPicture to create an AuxiliaryPicture object.
Properties
System capability: SystemCapability.Multimedia.Image.Core
writePixelsFromBuffer13+
writePixelsFromBuffer(data: ArrayBuffer): Promise<void>
Reads pixels from an ArrayBuffer and writes the data to this AuxiliaryPicture object. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| data | ArrayBuffer | Yes | Pixels of the auxiliary picture. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7600301 | Memory alloc failed. |
| 7600302 | Memory copy failed. |
Example
import { image } from '@kit.ImageKit';
async function WritePixelsFromBuffer() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(image.AuxiliaryPictureType.GAINMAP);
if(auxPictureObj != null) {
let auxBuffer: ArrayBuffer = await auxPictureObj.readPixelsToBuffer();
await auxPictureObj.writePixelsFromBuffer(auxBuffer);
console.info('Write pixels from buffer success.');
} else {
console.error('AuxPictureObj is null.');
}
}
readPixelsToBuffer13+
readPixelsToBuffer(): Promise<ArrayBuffer>
Reads pixels of this auxiliary picture and writes the data to an ArrayBuffer. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<ArrayBuffer> | Promise used to return the pixels of the auxiliary picture. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 7600301 | Memory alloc failed. |
| 7600302 | Memory copy failed. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function ReadPixelsToBuffer() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("hdr.jpg"); // Support for HDR images is required.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let auxPictureObj: image.AuxiliaryPicture | null = pictureObj.getAuxiliaryPicture(image.AuxiliaryPictureType.GAINMAP);
if(auxPictureObj != null) {
await auxPictureObj.readPixelsToBuffer().then((pixelsBuffer: ArrayBuffer) => {
console.info('Read pixels to buffer success.' );
}).catch((error: BusinessError) => {
console.error('Read pixels to buffer failed error.code: ' + JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
});
} else {
console.error('AuxPictureObj is null.');
}
}
getType13+
getType(): AuxiliaryPictureType
Obtains the type of this auxiliary picture.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| AuxiliaryPictureType | Type of the auxiliary picture. |
Example
import { image } from '@kit.ImageKit';
async function GetAuxiliaryPictureType() {
if (auxPictureObj != null) {
let type: image.AuxiliaryPictureType = auxPictureObj.getType();
console.info('Success get auxiliary picture type ' + JSON.stringify(type));
} else {
console.info('Failed get auxiliary picture type ');
}
}
setMetadata13+
setMetadata(metadataType: MetadataType, metadata: Metadata): Promise<void>
Sets the metadata for this auxiliary picture.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| metadataType | MetadataType | Yes | Metadata type, which is used to set the corresponding metadata. |
| metadata | Metadata | Yes | Metadata object. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7600202 | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function SetAuxPictureObjMetadata() {
const exifContext = getContext();
const exifResourceMgr = exifContext.resourceManager;
const exifRawFile = await exifResourceMgr.getRawFileContent("exif.jpg");// The image contains EXIF metadata.
let exifOps: image.SourceOptions = {
sourceDensity: 98,
}
let exifImageSource: image.ImageSource = image.createImageSource(exifRawFile.buffer as ArrayBuffer, exifOps);
let exifCommodityPixelMap: image.PixelMap = await exifImageSource.createPixelMap();
let exifPictureObj: image.Picture = image.createPicture(exifCommodityPixelMap);
if (exifPictureObj != null) {
console.info('Create picture succeeded');
} else {
console.info('Create picture failed');
}
if (auxPictureObj != null) {
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let exifMetaData: image.Metadata = await exifPictureObj.getMetadata(metadataType);
auxPictureObj.setMetadata(metadataType, exifMetaData).then(() => {
console.info('Set metadata success');
}).catch((error: BusinessError) => {
console.error('Set metadata failed.error.code: ${error.code}, error.message: ${error.message}');
});
} else {
console.info('AuxPictureObjMetaData is null');
}
}
getMetadata13+
getMetadata(metadataType: MetadataType): Promise<Metadata>
Obtains the metadata of this auxiliary picture.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| metadataType | MetadataType | Yes | Metadata type, which is used to obtain metadata of the corresponding type. |
Return value
| Type | Description |
|---|---|
| Promise<Metadata> | Metadata object. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
| 7600202 | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
Example
import { image } from '@kit.ImageKit';
async function GetAuxPictureObjMetadata() {
if (auxPictureObj != null) {
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let auxPictureObjMetaData: image.Metadata | null = await auxPictureObj.getMetadata(metadataType);
if (auxPictureObjMetaData != null) {
console.info('Get auxpictureobj Metadata success' );
} else {
console.info('Get auxpictureobj Metadata failed');
}
} else {
console.info('Get auxpictureobj is null.');
}
}
getAuxiliaryPictureinfo13+
getAuxiliaryPictureInfo(): AuxiliaryPictureInfo
Obtains the auxiliary picture information.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| AuxiliaryPictureInfo | Promise used to return the auxiliary picture information. |
Example
import { image } from '@kit.ImageKit';
async function GetAuxiliaryPictureInfo() {
if(auxPictureObj != null) {
let auxinfo: image.AuxiliaryPictureInfo = auxPictureObj.getAuxiliaryPictureInfo();
console.info('GetAuxiliaryPictureInfo Type: ' + auxinfo.auxiliaryPictureType +
' height: ' + auxinfo.size.height + ' width: ' + auxinfo.size.width +
' rowStride: ' + auxinfo.rowStride + ' pixelFormat: ' + auxinfo.pixelFormat +
' colorSpace: ' + auxinfo.colorSpace);
} else {
console.info('Get auxiliary picture information failed');
}
}
setAuxiliaryPictureinfo13+
setAuxiliaryPictureInfo(info: AuxiliaryPictureInfo): void
Sets the auxiliary picture information.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| info | AuxiliaryPictureInfo | Yes | Auxiliary picture information. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
Example
import { colorSpaceManager } from '@kit.ArkGraphics2D';
import { image } from '@kit.ImageKit';
async function SetAuxiliaryPictureInfo() {
if(auxPictureObj != null) {
let colorSpaceName = colorSpaceManager.ColorSpace.SRGB;
let info: image.AuxiliaryPictureInfo = {
auxiliaryPictureType: image.AuxiliaryPictureType.GAINMAP,
size: {height: 100, width: 200},
pixelFormat: image.PixelMapFormat.RGBA_8888,
rowStride: 0,
colorSpace: colorSpaceManager.create(colorSpaceName),
};
auxPictureObj.setAuxiliaryPictureInfo(info);
}
}
release13+
release():void
Releases this AuxiliaryPicture object. No value is returned.
System capability: SystemCapability.Multimedia.Image.Core
Example
import { image } from '@kit.ImageKit';
async function Release() {
let funcName = "Release";
if (auxPictureObj != null) {
auxPictureObj.release();
if (auxPictureObj.getType() == null) {
console.info(funcName, 'Success !');
} else {
console.info(funcName, 'Failed !');
}
} else {
console.info('PictureObj is null');
}
}
Metadata13+
A class used to store image metadata. For details about the supported metadata types, see MetadataType.
Properties
System capability: SystemCapability.Multimedia.Image.Core
getProperties13+
getProperties(key: Array<string>): Promise<Record<string, string | null>>
Obtains the values of properties from the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see PropertyKey and FragmentMapPropertyKey.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | Array<string> | Yes | Names of the properties. |
Return value
| Type | Description |
|---|---|
| Promise<Record<string, string | null>> | Promise used to return the property values. If the retrieval operation fails, an error code is returned. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
| 7600202 | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function GetProperties() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
if (metaData != null) {
await metaData.getProperties(["ImageWidth", "ImageLength"]).then((data2) => {
console.info('Get properties ',JSON.stringify(data2));
}).catch((error: BusinessError) => {
console.info('Get properties failed error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
});
} else {
console.info('Metadata is null.');
}
}
setProperties13+
setProperties(records: Record<string, string | null>): Promise<void>
Sets the values of properties for the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see PropertyKey and FragmentMapPropertyKey.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| records | Record<string, string | null> | Yes | Array of properties and their values. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. If the operation fails, an error code is returned. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed; |
| 7600202 | Unsupported metadata. Possible causes: 1. Unsupported metadata type. 2. The metadata type does not match the auxiliary picture type. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function SetProperties() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
if (metaData != null) {
let setkey: Record<string, string | null> = {
"ImageWidth": "200",
"ImageLength": "300"
};
await metaData.setProperties(setkey).then(async () => {
console.info('Set auxpictureobj properties success.');
}).catch((error: BusinessError) => {
console.error('Failed to set metadata Properties. code is ${error.code}, message is ${error.message}');
})
} else {
console.info('AuxPictureObj metadata is null. ');
}
}
getAllProperties13+
getAllProperties(): Promise<Record<string, string | null>>
Obtains all properties and values from the image's metadata. This API uses a promise to return the result. For details about how to obtain the property values, see PropertyKey and FragmentMapPropertyKey.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<Record<string, string | null>> | Promise used to return the values of all properties. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function GetAllProperties() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
if (metaData != null) {
await metaData.getAllProperties().then((data2) => {
const count = Object.keys(data2).length;
console.info('Metadata have ', count, ' properties');
console.info('Get metadata all properties: ', JSON.stringify(data2));
}).catch((error: BusinessError) => {
console.error('Get metadata all properties failed error.code: ' +JSON.stringify(error.code) + ' ,error.message:' + JSON.stringify(error.message));
});
} else {
console.info('Metadata is null.');
}
}
clone13+
clone(): Promise<Metadata>
Clones the metadata. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<Metadata> | Promise used to return the metadata instance. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 7600301 | Memory alloc failed. |
| 7600302 | Memory copy failed. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function clone() {
const context = getContext();
const resourceMgr = context.resourceManager;
const rawFile = await resourceMgr.getRawFileContent("exif.jpg"); // The image contains EXIF metadata.
let ops: image.SourceOptions = {
sourceDensity: 98,
}
let imageSource: image.ImageSource = image.createImageSource(rawFile.buffer as ArrayBuffer, ops);
let commodityPixelMap: image.PixelMap = await imageSource.createPixelMap();
let pictureObj: image.Picture = image.createPicture(commodityPixelMap);
let metadataType: image.MetadataType = image.MetadataType.EXIF_METADATA;
let metaData: image.Metadata | null = await pictureObj.getMetadata(metadataType);
if (metaData != null) {
let new_metadata: image.Metadata = await metaData.clone();
new_metadata.getProperties(["ImageWidth"]).then((data1) => {
console.info('Clone new_metadata and get Properties.', JSON.stringify(data1));
}).catch((err: BusinessError) => {
console.error('Clone new_metadata failed.', JSON.stringify(err));
});
} else {
console.info('Metadata is null.');
}
}
image.createImageReceiver11+
createImageReceiver(size: Size, format: ImageFormat, capacity: number): ImageReceiver
Creates an ImageReceiver instance by specifying the image size, format, and capacity.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | Size | Yes | Default size of the image. |
| format | ImageFormat | Yes | Image format, which is a constant of ImageFormat. (Currently, only ImageFormat:JPEG is supported. The format actually returned is determined by the producer, for example, camera.) |
| capacity | number | Yes | Maximum number of images that can be accessed at the same time. |
Return value
| Type | Description |
|---|---|
| ImageReceiver | Returns an ImageReceiver instance if the operation is successful. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types; |
Example
let size: image.Size = {
height: 8192,
width: 8
}
let receiver: image.ImageReceiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8);
image.createImageReceiver(deprecated)
createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver
Creates an ImageReceiver instance by specifying the image width, height, format, and capacity.
NOTE
This API is deprecated since API version 11. You are advised to use createImageReceiver.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| width | number | Yes | Default image width. |
| height | number | Yes | Default image height. |
| format | number | Yes | Image format, which is a constant of ImageFormat. (Currently, only ImageFormat:JPEG is supported. The format actually returned is determined by the producer, for example, camera.) |
| capacity | number | Yes | Maximum number of images that can be accessed at the same time. |
Return value
| Type | Description |
|---|---|
| ImageReceiver | Returns an ImageReceiver instance if the operation is successful. |
Example
let receiver: image.ImageReceiver = image.createImageReceiver(8192, 8, image.ImageFormat.JPEG, 8);
ImageReceiver9+
Provides APIs to obtain the surface ID of a component, read the latest image, read the next image, and release the ImageReceiver instance.
Before calling any APIs in ImageReceiver, you must create an ImageReceiver instance.
Properties
System capability: SystemCapability.Multimedia.Image.ImageReceiver
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| size | Size | Yes | No | Image size. |
| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time. |
| format | ImageFormat | Yes | No | Image format. |
getReceivingSurfaceId9+
getReceivingSurfaceId(callback: AsyncCallback<string>): void
Obtains a surface ID for the camera or other components. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the surface ID obtained. Otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.getReceivingSurfaceId((err: BusinessError, id: string) => {
if (err) {
console.error(`Failed to get the ReceivingSurfaceId.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in getting the ReceivingSurfaceId.');
}
});
getReceivingSurfaceId9+
getReceivingSurfaceId(): Promise<string>
Obtains a surface ID for the camera or other components. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Return value
| Type | Description |
|---|---|
| Promise<string> | Promise used to return the surface ID. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.getReceivingSurfaceId().then((id: string) => {
console.info('Succeeded in getting the ReceivingSurfaceId.');
}).catch((error: BusinessError) => {
console.error(`Failed to get the ReceivingSurfaceId.code ${error.code},message is ${error.message}`);
})
readLatestImage9+
readLatestImage(callback: AsyncCallback<Image>): void
Reads the latest image from the ImageReceiver instance. This API uses an asynchronous callback to return the result.
NOTE: This API can be called to receive data only after the on callback is triggered. When the Image object returned by this API is no longer needed, call release to release the object. New data can be received only after the release.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Image> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the latest image obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.readLatestImage((err: BusinessError, img: image.Image) => {
if (err) {
console.error(`Failed to read the latest Image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in reading the latest Image.');
}
});
readLatestImage9+
readLatestImage(): Promise<Image>
Reads the latest image from the ImageReceiver instance. This API uses a promise to return the result.
NOTE: This API can be called to receive data only after the on callback is triggered. When the Image object returned by this API is no longer needed, call release to release the object. New data can be received only after the release.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Return value
| Type | Description |
|---|---|
| Promise<Image> | Promise used to return the latest image. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.readLatestImage().then((img: image.Image) => {
console.info('Succeeded in reading the latest Image.');
}).catch((error: BusinessError) => {
console.error(`Failed to read the latest Image.code ${error.code},message is ${error.message}`);
})
readNextImage9+
readNextImage(callback: AsyncCallback<Image>): void
Reads the next image from the ImageReceiver instance. This API uses an asynchronous callback to return the result.
NOTE: This API can be called to receive data only after the on callback is triggered. When the Image object returned by this API is no longer needed, call release to release the object. New data can be received only after the release.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Image> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the next image obtained. Otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.readNextImage((err: BusinessError, img: image.Image) => {
if (err) {
console.error(`Failed to read the next Image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in reading the next Image.');
}
});
readNextImage9+
readNextImage(): Promise<Image>
Reads the next image from the ImageReceiver instance. This API uses a promise to return the result.
NOTE: This API can be called to receive data only after the on callback is triggered. When the Image object returned by this API is no longer needed, call release to release the object. New data can be received only after the release.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Return value
| Type | Description |
|---|---|
| Promise<Image> | Promise used to return the next image. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.readNextImage().then((img: image.Image) => {
console.info('Succeeded in reading the next Image.');
}).catch((error: BusinessError) => {
console.error(`Failed to read the next Image.code ${error.code},message is ${error.message}`);
})
on9+
on(type: 'imageArrival', callback: AsyncCallback<void>): void
Listens for image arrival events.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of event to listen for. The value is fixed at 'imageArrival', which is triggered when an image is received. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
receiver.on('imageArrival', () => {
// image arrival, do something.
})
off13+
off(type: 'imageArrival', callback?: AsyncCallback<void>): void
Unregisters the callback function that is triggered when the buffer is released.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of event, which is 'imageArrival'. |
| callback | AsyncCallback<void> | No | Callback to unregister. |
Example
let callbackFunc = ()=>{
// do something.
}
receiver.on('imageArrival', callbackFunc)
receiver.off('imageArrival', callbackFunc)
release9+
release(callback: AsyncCallback<void>): void
Releases this ImageReceiver instance. This API uses an asynchronous callback to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageReceiver object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release the receiver.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing the receiver.');
}
})
release9+
release(): Promise<void>
Releases this ImageReceiver instance. This API uses a promise to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageReceiver object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
receiver.release().then(() => {
console.info('Succeeded in releasing the receiver.');
}).catch((error: BusinessError) => {
console.error(`Failed to release the receiver.code ${error.code},message is ${error.message}`);
})
image.createImageCreator11+
createImageCreator(size: Size, format: ImageFormat, capacity: number): ImageCreator
Creates an ImageCreator instance by specifying the image size, format, and capacity.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | Size | Yes | Default size of the image. |
| format | ImageFormat | Yes | Image format, for example, YCBCR_422_SP or JPEG. |
| capacity | number | Yes | Maximum number of images that can be accessed at the same time. |
Return value
| Type | Description |
|---|---|
| ImageCreator | Returns an ImageCreator instance if the operation is successful. |
Error codes
For details about the error codes, see Image Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types; |
Example
let size: image.Size = {
height: 8192,
width: 8
}
let creator: image.ImageCreator = image.createImageCreator(size, image.ImageFormat.JPEG, 8);
image.createImageCreator(deprecated)
createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator
Creates an ImageCreator instance by specifying the image width, height, format, and capacity.
NOTE
This API is deprecated since API version 11. You are advised to use createImageCreator.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| width | number | Yes | Default image width. |
| height | number | Yes | Default image height. |
| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. |
| capacity | number | Yes | Maximum number of images that can be accessed at the same time. |
Return value
| Type | Description |
|---|---|
| ImageCreator | Returns an ImageCreator instance if the operation is successful. |
Example
let creator: image.ImageCreator = image.createImageCreator(8192, 8, image.ImageFormat.JPEG, 8);
ImageCreator9+
Provides APIs for applications to request an image native data area and compile native image data. Before calling any APIs in ImageCreator, you must create an ImageCreator instance. ImageCreator does not support multiple threads.
Properties
System capability: SystemCapability.Multimedia.Image.ImageCreator
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time. |
| format | ImageFormat | Yes | No | Image format. |
dequeueImage9+
dequeueImage(callback: AsyncCallback<Image>): void
Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Image> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the latest image obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.dequeueImage((err: BusinessError, img: image.Image) => {
if (err) {
console.error(`Failed to dequeue the Image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in dequeuing the Image.');
}
});
dequeueImage9+
dequeueImage(): Promise<Image>
Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Return value
| Type | Description |
|---|---|
| Promise<Image> | Promise used to return the latest image. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.dequeueImage().then((img: image.Image) => {
console.info('Succeeded in dequeuing the Image.');
}).catch((error: BusinessError) => {
console.error(`Failed to dequeue the Image.code ${error.code},message is ${error.message}`);
})
queueImage9+
queueImage(interface: Image, callback: AsyncCallback<void>): void
Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| interface | Image | Yes | Drawn image. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.dequeueImage().then((img: image.Image) => {
// Draw the image.
img.getComponent(4).then((component : image.Component) => {
let bufferArr: Uint8Array = new Uint8Array(component.byteBuffer);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 0; //B
bufferArr[i + 1] = 0; //G
bufferArr[i + 2] = 255; //R
bufferArr[i + 3] = 255; //A
}
})
creator.queueImage(img, (err: BusinessError) => {
if (err) {
console.error(`Failed to queue the Image.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in queuing the Image.');
}
})
})
queueImage9+
queueImage(interface: Image): Promise<void>
Places the drawn image in the dirty queue. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| interface | Image | Yes | Drawn image. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.dequeueImage().then((img: image.Image) => {
// Draw the image.
img.getComponent(4).then((component: image.Component) => {
let bufferArr: Uint8Array = new Uint8Array(component.byteBuffer);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 0; //B
bufferArr[i + 1] = 0; //G
bufferArr[i + 2] = 255; //R
bufferArr[i + 3] = 255; //A
}
})
creator.queueImage(img).then(() => {
console.info('Succeeded in queuing the Image.');
}).catch((error: BusinessError) => {
console.error(`Failed to queue the Image.code ${error.code},message is ${error.message}`);
})
})
on9+
on(type: 'imageRelease', callback: AsyncCallback<void>): void
Listens for image release events. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of event, which is 'imageRelease'. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.on('imageRelease', (err: BusinessError) => {
if (err) {
console.error(`Failed to get the imageRelease callback.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in getting imageRelease callback.');
}
})
off13+
off(type: 'imageRelease', callback?: AsyncCallback<void>): void
Unregisters the callback function that is triggered when the buffer is released.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of event, which is 'imageRelease'. |
| callback | AsyncCallback<void> | No | Callback to unregister. |
Example
let callbackFunc = ()=>{
// do something.
}
creator.on('imageRelease', callbackFunc)
creator.off('imageRelease', callbackFunc)
release9+
release(callback: AsyncCallback<void>): void
Releases this ImageCreator instance. This API uses an asynchronous callback to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageCreator object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release the creator.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing creator.');
}
});
release9+
release(): Promise<void>
Releases this ImageCreator instance. This API uses a promise to return the result.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the ImageCreator object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.ImageCreator
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
creator.release().then(() => {
console.info('Succeeded in releasing creator.');
}).catch((error: BusinessError) => {
console.error(`Failed to release the creator.code ${error.code},message is ${error.message}`);
})
Image9+
Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An Image instance is returned when readNextImage and readLatestImage are called.
Properties
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable | Writable | Description |
|---|---|---|---|---|
| clipRect | Region | Yes | Yes | Image area to be cropped. |
| size | Size | Yes | No | Image size. If the image object stores the camera preview stream data (YUV image data), the width and height in size obtained correspond to those of the YUV image. If the image object stores the camera photo stream data (JPEG image data, which is already encoded), the width in size obtained is the JPEG data size, and the height is 1. The type of data stored in the image object depends on whether the application passes the surface ID in the receiver to a previewOutput or captureOutput object of the camera. For details about the best practices of camera preview and photo capture, see Dual-Channel Preview (ArkTS) and Photo Capture Sample (ArkTS). |
| format | number | Yes | No | Image format. For details, see OH_NativeBuffer_Format. |
| timestamp12+ | number | Yes | No | Image timestamp. Timestamps, measured in nanoseconds, are usually monotonically increasing. The specific meaning and baseline of these timestamps are determined by the image producer, which is the camera in the camera preview and photo scenarios. As a result, images from different producers may carry timestamps with distinct meanings and baselines, making direct comparison between them infeasible. To obtain the generation time of a photo, you can use getImageProperty to read the related EXIF information. |
getComponent9+
getComponent(componentType: ComponentType, callback: AsyncCallback<Component>): void
Obtains the component buffer from the Image instance based on the color component type. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| componentType | ComponentType | Yes | Color component type of the image. (Currently, only ComponentType:JPEG is supported. The format actually returned is determined by the producer, for example, camera.) |
| callback | AsyncCallback<Component> | Yes | Callback used to return the result. If the operation is successful, err is undefined and data is the component buffer obtained; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
img.getComponent(4, (err: BusinessError, component: image.Component) => {
if (err) {
console.error(`Failed to get the component.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in getting component.');
}
})
getComponent9+
getComponent(componentType: ComponentType): Promise<Component>
Obtains the component buffer from the Image instance based on the color component type. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| componentType | ComponentType | Yes | Color component type of the image. (Currently, only ComponentType:JPEG is supported. The format actually returned is determined by the producer, for example, camera.) |
Return value
| Type | Description |
|---|---|
| Promise<Component> | Promise used to return the component buffer. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
img.getComponent(4).then((component: image.Component) => {
console.info('Succeeded in getting component.');
}).catch((error: BusinessError) => {
console.error(`Failed to get the component.code ${error.code},message is ${error.message}`);
})
release9+
release(callback: AsyncCallback<void>): void
Releases this Image instance. This API uses an asynchronous callback to return the result.
The corresponding resources must be released before another image arrives.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the Image object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
img.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release the image instance.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing the image instance.');
}
})
release9+
release(): Promise<void>
Releases this Image instance. This API uses a promise to return the result.
The corresponding resources must be released before another image arrives.
ArkTS supports memory reclamation. Even if the application does not call release(), the memory of the Image object will be released by the system. However, images usually occupy a large amount of memory. Therefore, it is recommended that the application proactively call the API to release the memory when the object is no longer required.
System capability: SystemCapability.Multimedia.Image.Core
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
img.release().then(() => {
console.info('Succeeded in releasing the image instance.');
}).catch((error: BusinessError) => {
console.error(`Failed to release the image instance.code ${error.code},message is ${error.message}`);
})
PositionArea7+
Describes area information in an image.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| pixels | ArrayBuffer | No | No | Pixels of the image. Only pixel data in BGRA_8888 format is supported. |
| offset | number | No | No | Offset for data reading. |
| stride | number | No | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of stride must be greater than or equal to the value of region.size.width multiplied by 4. |
| region | Region | No | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image. |
ImageInfo
Describes image information.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| size6+ | Size | No | No | Image size. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| density9+ | number | No | No | Pixel density, in ppi. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| stride11+ | number | No | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory.stride >= region.size.width*4 Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| pixelFormat12+ | PixelMapFormat | No | No | Pixel format. Atomic service API: This API can be used in atomic services since API version 12. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| alphaType12+ | AlphaType | No | No | Alpha type. Atomic service API: This API can be used in atomic services since API version 12. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| mimeType12+ | string | No | No | Actual image format (MIME type). |
| isHdr12+ | boolean | No | No | Whether the image is an HDR image. For ImageSource, this parameter specifies whether the source image is in HDR format. For PixelMap, this parameter specifies whether the decoded PixelMap is in HDR format. |
Size
Describes the size of an image.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| height | number | No | No | Image height, in px. |
| width | number | No | No | Image width, in px. |
PixelMapFormat7+
Enumerates the pixel formats of images.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| UNKNOWN | 0 | Unknown format. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| RGB_565 | 2 | RGB_565. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| RGBA_8888 | 3 | RGBA_8888. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| BGRA_88889+ | 4 | BGRA_8888. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| RGB_8889+ | 5 | RGB_888. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| ALPHA_89+ | 6 | ALPHA_8. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| RGBA_F169+ | 7 | RGBA_F16. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| NV219+ | 8 | NV21. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| NV129+ | 9 | NV12. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| RGBA_101010212+ | 10 | RGBA_1010102. |
| YCBCR_P01012+ | 11 | YCBCR_P010. |
| YCRCB_P01012+ | 12 | YCRCB_P010. |
AlphaType9+
Enumerates the alpha types of images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| UNKNOWN | 0 | Unknown alpha type. |
| OPAQUE | 1 | There is no alpha or the image is opaque. |
| PREMUL | 2 | Premultiplied alpha. |
| UNPREMUL | 3 | RGB non-premultiplied alpha. |
AuxiliaryPictureType13+
Enumerates the auxiliary pictures types.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| GAINMAP | 1 | Gain map, a mechanism for transforming an SDR image into an HDR image capable of display adjustment. It is a set of combinations describing how to apply gain map metadata. |
| DEPTH_MAP | 2 | Depth map, which stores the depth data of an image. It captures the distance between each pixel and the camera to provide 3D scene structure. It is usually used for 3D modeling and scene comprehension. |
| UNREFOCUS_MAP | 3 | Defocused portrait original image, which provides a method to emphasize background blur in portrait photographing. It helps users select a focus region in post-processing, allowing for greater creative control. |
| LINEAR_MAP | 4 | Linear map, which is used to provide additional viewpoints or supplementary information. It is usually used to enhance visual effects and can contain linear representations of lighting, colors, or other visual elements in a scene. |
| FRAGMENT_MAP | 5 | Fragment map, which indicates regions obscured by watermarks in the original image. It is used to remove or correct the watermark interference, thereby enhancing the image completeness and visibility. |
AuxiliaryPictureInfo13+
Describes the auxiliary picture information.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| auxiliaryPictureType | AuxiliaryPictureType | No | No | Auxiliary picture type. |
| size | Size | No | No | Image size. |
| rowStride | number | No | No | Row stride. |
| pixelFormat | PixelMapFormat | No | No | Pixel format. |
| colorSpace | colorSpaceManager.ColorSpaceManager | No | No | Color space. |
MetadataType13+
Enumerates image metadata types.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| EXIF_METADATA | 1 | EXIF data. |
| FRAGMENT_METADATA | 2 | Fragment map metadata. |
ScaleMode9+
Enumerates the scale modes of images.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra. |
| FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. |
SourceOptions9+
Defines image source initialization options.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| sourceDensity | number | No | No | Pixel density of the image resource, in DPI. If desiredSize is not set in [DecodingOptions](# decodingoptions7) and SourceOptions.sourceDensity and DecodingOptions.fitDensity are not 0, the PixelMap output after decoding will be scaled. The formula for calculating the width after scaling is as follows (the same applies to the height): (width * fitDensity + (sourceDensity >> 1)) / sourceDensity. |
| sourcePixelFormat | PixelMapFormat | No | Yes | Image pixel format. The default value is UNKNOWN. |
| sourceSize | Size | No | Yes | Image pixel size. The default value is null. |
InitializationOptions8+
Defines PixelMap initialization options.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| alphaType9+ | AlphaType | No | Yes | Alpha type. The default value is IMAGE_ALPHA_TYPE_PREMUL. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| editable | boolean | No | Yes | Whether the image is editable. The default value is false. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| srcPixelFormat12+ | PixelMapFormat | No | Yes | Pixel format of the passed-in buffer data. The default value is BGRA_8888. |
| pixelFormat | PixelMapFormat | No | Yes | Pixel format of the generated PixelMap. The default value is RGBA_8888. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| scaleMode9+ | ScaleMode | No | Yes | Scale mode. The default value is 0. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| size | Size | No | No | Image size. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
DecodingOptions7+
Describes the image decoding options.
System capability: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| sampleSize | number | No | Yes | Sampling size of the thumbnail. The default value is 1. Currently, the value can only be 1. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| rotate | number | No | Yes | Rotation angle. The default value is 0. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| editable | boolean | No | Yes | Whether the image is editable. The default value is false. If this option is set to false, the image cannot be edited again, and operations such as writing pixels will fail. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| desiredSize | Size | No | Yes | Expected output size. The default value is null. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| desiredRegion | Region | No | Yes | Region to decode. The default value is null. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| desiredPixelFormat | PixelMapFormat | No | Yes | Pixel format for decoding. The default value is RGBA_8888. Only RGBA_8888, BGRA_8888, and RGB_565 are supported. RGB_565 is not supported for images with alpha channels, such as PNG, GIF, ICO, and WEBP. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| index | number | No | Yes | Index of the image to decode. The default value is 0. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| fitDensity9+ | number | No | Yes | Pixel density, in ppi. The default value is 0. Atomic service API: This API can be used in atomic services since API version 11. Widget capability: This API can be used in ArkTS widgets since API version 12. |
| desiredColorSpace11+ | colorSpaceManager.ColorSpaceManager | No | Yes | Target color space. The default value is UNKNOWN. |
| desiredDynamicRange12+ | DecodingDynamicRange | No | Yes | Desired dynamic range. The default value is SDR. This property cannot be set for an image source created using CreateIncrementalSource. By default, the image source is decoded as SDR content. If the platform does not support HDR, the setting is invalid and the content is decoded as SDR content by default. |
DecodingOptionsForPicture13+
Describes the image decoding options.
System capability: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| desiredAuxiliaryPictures | Array<AuxiliaryPictureType> | No | No | Auxiliary picture type. By default, all auxiliary picture types are decoded. |
Region8+
Describes the region information.
Widget capability: This API can be used in ArkTS widgets since API version 12.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| size7+ | Size | No | No | Region size. |
| x7+ | number | No | No | X coordinate of the region. |
| y7+ | number | No | No | Y coordinate of the region. |
PackingOption
Describes the options for image packing.
System capability: SystemCapability.Multimedia.Image.ImagePacker
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| format | string | No | No | Format of the packed image. Currently, only the following formats are supported: image/jpeg, image/webp, image/png, and image/heic (or image/heif)12+ (depending on the hardware). NOTE: The JPEG format does not support the alpha channel. If the JPEG format with the alpha channel is used for data encoding, the transparent color turns black. Atomic service API: This API can be used in atomic services since API version 11. |
| quality | number | No | No | Quality of the output image in JPEG encoding. The value ranges from 0 to 100. The value 0 means the lowest quality, and 100 means the highest quality. The higher the quality, the larger the space occupied by the generated image. Atomic service API: This API can be used in atomic services since API version 11. |
| bufferSize9+ | number | No | Yes | Size of the buffer for receiving the encoded data, in bytes. If this parameter is not set, the default value 25 MB is used. If the size of an image exceeds 25 MB, you must specify the size. The value of bufferSize must be greater than the size of the encoded image. The use of packToFile is not restricted by this parameter. Atomic service API: This API can be used in atomic services since API version 11. |
| desiredDynamicRange12+ | PackingDynamicRange | No | Yes | Desired dynamic range. The default value is SDR. |
| needsPackProperties12+ | boolean | No | Yes | Whether to encode image property information, for example, EXIF. The value true means to encode image property information, and false means the opposite. The default value is false. |
ImagePropertyOptions11+
Describes the image properties.
System capability: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| index | number | Yes | Yes | Index of the image. The default value is 0. |
| defaultValue | string | Yes | Yes | Default property value. The default value is null. |
GetImagePropertyOptions(deprecated)
Describes the image properties.
NOTE
This API is deprecated since API version 11. You are advised to use ImagePropertyOptions.
System capability: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| index | number | No | Yes | Index of the image. The default value is 0. |
| defaultValue | string | No | Yes | Default property value. The default value is null. |
PropertyKey7+
Describes the exchangeable image file format (EXIF) data of an image.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| NEW_SUBFILE_TYPE 12+ | "NewSubfileType" | Read/Write capability: readable and writable Data type of a subfile, such as a full-resolution image, a thumbnail, or a part of a multi-frame image. The value is a bit mask. The value 0 indicates a full-resolution image, 1 indicates a thumbnail, and 2 indicates a part of a multi-frame image. |
| SUBFILE_TYPE 12+ | "SubfileType" | Read/Write capability: readable and writable Type of data contained in this subfile. This tag has been deprecated. Use NewSubfileType instead. |
| IMAGE_WIDTH | "ImageWidth" | Read/Write capability: readable and writable Image width. |
| IMAGE_LENGTH | "ImageLength" | Read/Write capability: readable and writable Image length. |
| BITS_PER_SAMPLE | "BitsPerSample" | Read/Write capability: readable and writable Number of bits per sample. For example, for RGB, which has three components, the format is 8, 8, 8. |
| COMPRESSION 12+ | "Compression" | Read/Write capability: readable and writable Compression scheme used on the image data. |
| PHOTOMETRIC_INTERPRETATION 12+ | "PhotometricInterpretation" | Read/Write capability: readable and writable Color space of the image data, for example, RGB or YCbCr. |
| IMAGE_DESCRIPTION10+ | "ImageDescription" | Read/Write capability: readable and writable Image description. |
| MAKE10+ | "Make" | Read/Write capability: readable and writable Manufacturer. |
| MODEL10+ | "Model" | Read/Write capability: readable and writable Device model. |
| STRIP_OFFSETS 12+ | "StripOffsets" | Read/Write capability: readable and writable Byte offset of each strip. |
| ORIENTATION | "Orientation" | Read/Write capability: readable and writable Image orientation. - 1: Top-left: The image is not rotated. - 2: Top-right: The image is flipped horizontally. - 3: Bottom-right: The image is rotated by 180°. - 4: Bottom-left: The image is flipped vertically. - 5: Left-top: The image is flipped horizontally and then rotated clockwise by 270°. - 6: Right-top: The image is rotated clockwise by 90°. - 7: Right-bottom: The image is vertically flipped and then rotated clockwise by 90°. - 8: Left-bottom: The image is rotated clockwise by 270°. - Unknown Value: No value is defined. |
| SAMPLES_PER_PIXEL 12+ | "SamplesPerPixel" | Read/Write capability: readable and writable Number of components per pixel. The value is 3 for RGB and YCbCr images. The JPEG key is used in JPEG compressed data. |
| ROWS_PER_STRIP 12+ | "RowsPerStrip" | Read/Write capability: readable and writable Number of rows per strip. |
| STRIP_BYTE_COUNTS 12+ | "StripByteCounts" | Read/Write capability: readable and writable Number of bytes in each strip after compression. |
| X_RESOLUTION 12+ | "XResolution" | Read/Write capability: readable and writable Number of pixels per ResolutionUnit in the image width (X) direction. |
| Y_RESOLUTION 12+ | "YResolution" | Read/Write capability: readable and writable Number of pixels per ResolutionUnit in the image height (Y) direction. |
| PLANAR_CONFIGURATION 12+ | "PlanarConfiguration" | Read/Write capability: readable and writable Storage format of components of each pixel, which can be chunky or planar. |
| RESOLUTION_UNIT 12+ | "ResolutionUnit" | Read/Write capability: readable and writable Unit of measurement for XResolution and YResolution. |
| TRANSFER_FUNCTION 12+ | "TransferFunction" | Read/Write capability: readable and writable Transfer function for the image, which is usually used for color correction. |
| SOFTWARE 12+ | "Software" | Read/Write capability: readable and writable Name and version number of the software used to create the image. |
| DATE_TIME10+ | "DateTime" | Read/Write capability: readable and writable Date and time of image creation. An example in the correct format is 2024:01:25 05:51:34. |
| ARTIST 12+ | "Artist" | Read/Write capability: readable and writable Person who created the image. |
| WHITE_POINT 12+ | "WhitePoint" | Read/Write capability: readable and writable Chromaticity of the white point of the image. |
| PRIMARY_CHROMATICITIES 12+ | "PrimaryChromaticities" | Read/Write capability: readable and writable Chromaticities of the primaries of the image. |
| PHOTO_MODE10+ | "PhotoMode" | Read/Write capability: readable and writable Photographing mode. |
| JPEG_INTERCHANGE_FORMAT 12+ | "JPEGInterchangeFormat" | Read/Write capability: readable and writable Offset of the SOI marker of a JPEG interchange format bitstream. |
| JPEG_INTERCHANGE_FORMAT_LENGTH 12+ | "JPEGInterchangeFormatLength" | Read/Write capability: readable and writable Number of bytes of the JPEG stream. |
| YCBCR_COEFFICIENTS 12+ | "YCbCrCoefficients" | Read/Write capability: readable and writable Transformation from RGB to YCbCr image data. |
| YCBCR_SUB_SAMPLING 12+ | "YCbCrSubSampling" | Read/Write capability: readable and writable Subsampling factors used for the chrominance components of a YCbCr image. |
| YCBCR_POSITIONING 12+ | "YCbCrPositioning" | Read/Write capability: readable and writable Positioning of subsampled chrominance components relative to luminance samples. |
| REFERENCE_BLACK_WHITE 12+ | "ReferenceBlackWhite" | Read/Write capability: readable and writable A pair of headroom and footroom image data values (codes) for each pixel component. |
| COPYRIGHT 12+ | "Copyright" | Read/Write capability: readable and writable Copyright notice of the image. |
| EXPOSURE_TIME9+ | "ExposureTime" | Read/Write capability: readable and writable Exposure time, for example, 1/33 seconds. |
| F_NUMBER9+ | "FNumber" | Read/Write capability: readable and writable F number, for example, f/1.8. |
| EXPOSURE_PROGRAM 12+ | "ExposureProgram" | Read/Write capability: readable and writable Class of the program used by the camera to set exposure when the image was captured. |
| SPECTRAL_SENSITIVITY 12+ | "SpectralSensitivity" | Read/Write capability: readable and writable Spectral sensitivity of each channel of the camera. |
| GPS_VERSION_ID 12+ | "GPSVersionID" | Read/Write capability: readable and writable Version of GPSInfoIFD. |
| GPS_LATITUDE_REF | "GPSLatitudeRef" | Read/Write capability: readable and writable Whether the latitude is north or south latitude. |
| GPS_LATITUDE | "GPSLatitude" | Read/Write capability: readable and writable Image latitude. The value must be in the format of degree,minute,second, for example, 39,54,7.542. |
| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Read/Write capability: readable and writable Whether the longitude is east or west longitude. |
| GPS_LONGITUDE | "GPSLongitude" | Read/Write capability: readable and writable Image longitude. The value must be in the format of degree,minute,second, for example, 116,19,42.16. |
| GPS_ALTITUDE_REF 12+ | "GPSAltitudeRef" | Read/Write capability: readable and writable Whether the latitude is north or south latitude. |
| GPS_ALTITUDE 12+ | "GPSAltitude" | Read/Write capability: readable and writable Altitude based on the reference in GPSAltitudeRef. |
| GPS_TIME_STAMP10+ | "GPSTimeStamp" | Read/Write capability: readable and writable GPS timestamp. |
| GPS_SATELLITES 12+ | "GPSSatellites" | Read/Write capability: readable and writable GPS satellites used for measurement. |
| GPS_STATUS 12+ | "GPSStatus" | Read/Write capability: readable and writable Status of the GPS receiver when the image was recorded. |
| GPS_MEASURE_MODE 12+ | "GPSMeasureMode" | Read/Write capability: readable and writable GPS measurement pmode. |
| GPS_DOP 12+ | "GPSDOP" | Read/Write capability: readable and writable GPS DOP (data degree of precision) |
| GPS_SPEED_REF 12+ | "GPSSpeedRef" | Read/Write capability: readable and writable Unit used to express the movement speed of the GPS receiver. |
| GPS_SPEED 12+ | "GPSSpeed" | Read/Write capability: readable and writable Movement speed of the GPS receiver. |
| GPS_TRACK_REF 12+ | "GPSTrackRef" | Read/Write capability: readable and writable Reference of the movement direction of the GPS receiver. |
| GPS_TRACK 12+ | "GPSTrack" | Read/Write capability: readable and writable Movement direction of the GPS receiver. |
| GPS_IMG_DIRECTION_REF 12+ | "GPSImgDirectionRef" | Read/Write capability: readable and writable Reference of the direction of the image when it was captured. |
| GPS_IMG_DIRECTION 12+ | "GPSImgDirection" | Read/Write capability: readable and writable Direction of the image when it was captured. |
| GPS_MAP_DATUM 12+ | "GPSMapDatum" | Read/Write capability: readable and writable Geodetic survey data used by the GPS receiver. |
| GPS_DEST_LATITUDE_REF 12+ | "GPSDestLatitudeRef" | Read/Write capability: readable and writable Whether the latitude of the destination point is north or south latitude. |
| GPS_DEST_LATITUDE 12+ | "GPSDestLatitude" | Read/Write capability: readable and writable Latitude of the destination point. |
| GPS_DEST_LONGITUDE_REF 12+ | "GPSDestLongitudeRef" | Read/Write capability: readable and writable Whether the longitude of the destination point is east or west longitude. |
| GPS_DEST_LONGITUDE 12+ | "GPSDestLongitude" | Read/Write capability: readable and writable Longitude of the destination point. |
| GPS_DEST_BEARING_REF 12+ | "GPSDestBearingRef" | Read/Write capability: readable and writable Reference of the bearing to the destination point. |
| GPS_DEST_BEARING 12+ | "GPSDestBearing" | Read/Write capability: readable and writable Bearing to the destination point. |
| GPS_DEST_DISTANCE_REF 12+ | "GPSDestDistanceRef" | Read/Write capability: readable and writable Unit used to express the distance to the destination point. |
| GPS_DEST_DISTANCE 12+ | "GPSDestDistance" | Read/Write capability: readable and writable Distance to the destination point. |
| GPS_PROCESSING_METHOD 12+ | "GPSProcessingMethod" | Read/Write capability: readable and writable String that records the name of the method used for positioning. |
| GPS_AREA_INFORMATION 12+ | "GPSAreaInformation" | Read/Write capability: readable and writable String that records the name of the GPS area. |
| GPS_DATE_STAMP10+ | "GPSDateStamp" | Read/Write capability: readable and writable GPS date stamp. |
| GPS_DIFFERENTIAL 12+ | "GPSDifferential" | Read/Write capability: readable and writable Whether differential correction is applied to the GPS receiver. It is critical to accurate location accuracy. |
| GPS_H_POSITIONING_ERROR 12+ | "GPSHPositioningError" | Read/Write capability: readable and writable Horizontal positioning error, in meters. |
| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | Read/Write capability: readable and writable ISO sensitivity or ISO speed, for example, 400. |
| PHOTOGRAPHIC_SENSITIVITY 12+ | "PhotographicSensitivity" | Read/Write capability: readable and writable Sensitivity of the camera or input device when the image was captured. |
| OECF 12+ | "OECF" | Read/Write capability: readable and writable Opto-Electric Conversion Function (OECF) specified in ISO 14524. |
| SENSITIVITY_TYPE10+ | "SensitivityType" | Read/Write capability: readable and writable Sensitivity type. |
| STANDARD_OUTPUT_SENSITIVITY10+ | "StandardOutputSensitivity" | Read/Write capability: readable and writable Standard output sensitivity. |
| RECOMMENDED_EXPOSURE_INDEX10+ | "RecommendedExposureIndex" | Read/Write capability: readable and writable Recommended exposure index. |
| ISO_SPEED10+ | "ISOSpeedRatings" | Read/Write capability: readable and writable ISO speed. |
| ISO_SPEED_LATITUDE_YYY 12+ | "ISOSpeedLatitudeyyy" | Read/Write capability: readable and writable ISO speed latitude yyy value of the camera or input device, which is defined in ISO 12232. |
| ISO_SPEED_LATITUDE_ZZZ 12+ | "ISOSpeedLatitudezzz" | Read/Write capability: readable and writable ISO speed latitude zzz value of the camera or input device, which is defined in ISO 12232. |
| EXIF_VERSION 12+ | "ExifVersion" | Read/Write capability: readable and writable Version of the supported EXIF standard. |
| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Read/Write capability: readable and writable Time when the original image data was generated, for example, 2022:09:06 15:48:00. |
| DATE_TIME_DIGITIZED 12+ | "DateTimeDigitized" | Read/Write capability: readable and writable Date and time when the image was stored as digital data, in the format of YYYY:MM:DD HH:MM:SS. |
| OFFSET_TIME 12+ | "OffsetTime" | Read/Write capability: readable and writable Time with an offset from UTC when the image was captured, in the format of ±HH:MM. |
| OFFSET_TIME_ORIGINAL 12+ | "OffsetTimeOriginal" | Read/Write capability: readable and writable Time with an offset from UTC when the original image was created. It is critical for time-sensitive applications. |
| OFFSET_TIME_DIGITIZED 12+ | "OffsetTimeDigitized" | Read/Write capability: readable and writable Time with an offset from UTC when the image was digitized. It helps to accurately adjust the timestamp. |
| COMPONENTS_CONFIGURATION 12+ | "ComponentsConfiguration" | Read/Write capability: readable and writable Specific information about compressed data. |
| COMPRESSED_BITS_PER_PIXEL 12+ | "CompressedBitsPerPixel" | Read/Write capability: readable and writable Number of bits per pixel. It is specific to compressed data. |
| SHUTTER_SPEED 12+ | "ShutterSpeedValue" | Read/Write capability: readable and writable Shutter speed, expressed in Additive System of Photographic Exposure (APEX) values. |
| APERTURE_VALUE10+ | "ApertureValue" | Read/Write capability: readable and writable Lens aperture. An example in the correct format is 4/1. |
| BRIGHTNESS_VALUE 12+ | "BrightnessValue" | Read/Write capability: readable and writable Value of brightness, expressed in APEX values. |
| EXPOSURE_BIAS_VALUE10+ | "ExposureBiasValue" | Read/Write capability: readable and writable Exposure bias. |
| MAX_APERTURE_VALUE 12+ | "MaxApertureValue" | Read/Write capability: readable and writable Smallest F number of the lens. |
| SUBJECT_DISTANCE 12+ | "SubjectDistance" | Read/Write capability: readable and writable Distance to the subject, in meters. |
| METERING_MODE10+ | "MeteringMode" | Read/Write capability: readable and writable Metering mode. |
| LIGHT_SOURCE10+ | "LightSource" | Read/Write capability: readable and writable Light source. An example value is Fluorescent. |
| FLASH 10+ | "Flash" | Read/Write capability: readable and writable Flash status. |
| FOCAL_LENGTH 10+ | "FocalLength" | Read/Write capability: readable and writable Focal length of the lens. |
| SUBJECT_AREA 12+ | "SubjectArea" | Read/Write capability: readable and writable Location and area of the main subject in the entire scene. |
| MAKER_NOTE 12+ | "MakerNote" | Read/Write capability: read-only Marker used by EXIF/DCF manufacturers to record any required information. |
| SCENE_POINTER 12+ | "HwMnoteScenePointer" | Read/Write capability: read-only Pointer to the scene. |
| SCENE_VERSION 12+ | "HwMnoteSceneVersion" | Read/Write capability: read-only Scene algorithm version. |
| SCENE_FOOD_CONF11+ | "HwMnoteSceneFoodConf" | Read/Write capability: read-only Photographing scene: food. |
| SCENE_STAGE_CONF11+ | "HwMnoteSceneStageConf" | Read/Write capability: read-only Photographing scene: stage. |
| SCENE_BLUE_SKY_CONF11+ | "HwMnoteSceneBlueSkyConf" | Read/Write capability: read-only Photographing scene: blue sky. |
| SCENE_GREEN_PLANT_CONF11+ | "HwMnoteSceneGreenPlantConf" | Read/Write capability: read-only Photographing scene: green plant. |
| SCENE_BEACH_CONF11+ | "HwMnoteSceneBeachConf" | Read/Write capability: read-only Photographing scene: beach. |
| SCENE_SNOW_CONF11+ | "HwMnoteSceneSnowConf" | Read/Write capability: read-only Photographing scene: snow. |
| SCENE_SUNSET_CONF11+ | "HwMnoteSceneSunsetConf" | Read/Write capability: read-only Photographing scene: sunset. |
| SCENE_FLOWERS_CONF11+ | "HwMnoteSceneFlowersConf" | Read/Write capability: read-only Photographing scene: flowers. |
| SCENE_NIGHT_CONF11+ | "HwMnoteSceneNightConf" | Read/Write capability: read-only Photographing scene: night. |
| SCENE_TEXT_CONF11+ | "HwMnoteSceneTextConf" | Read/Write capability: read-only Photographing scene: text. |
| FACE_POINTER 12+ | "HwMnoteFacePointer" | Read/Write capability: read-only Face pointer. |
| FACE_VERSION 12+ | "HwMnoteFaceVersion" | Read/Write capability: read-only Facial recognition algorithm version. |
| FACE_COUNT11+ | "HwMnoteFaceCount" | Read/Write capability: read-only Number of faces. |
| FACE_CONF 12+ | "HwMnoteFaceConf" | Read/Write capability: read-only Face confidence. |
| FACE_SMILE_SCORE 12+ | "HwMnoteFaceSmileScore" | Read/Write capability: read-only Smile score of for faces. |
| FACE_RECT 12+ | "HwMnoteFaceRect" | Read/Write capability: read-only Face rectangle. |
| FACE_LEYE_CENTER 12+ | "HwMnoteFaceLeyeCenter" | Read/Write capability: read-only Left eye centered. |
| FACE_REYE_CENTER 12+ | "HwMnoteFaceReyeCenter" | Read/Write capability: read-only Right eye centered. |
| FACE_MOUTH_CENTER 12+ | "HwMnoteFaceMouthCenter" | Read/Write capability: read-only Mouth centered. |
| CAPTURE_MODE 10+ | "HwMnoteCaptureMode" | Read/Write capability: readable and writable Capture mode. |
| BURST_NUMBER 12+ | "HwMnoteBurstNumber" | Read/Write capability: read-only Number of burst shooting times. |
| FRONT_CAMERA 12+ | "HwMnoteFrontCamera" | Read/Write capability: read-only Whether the front camera is used to take a selfie. |
| ROLL_ANGLE 11+ | "HwMnoteRollAngle" | Read/Write capability: read-only Roll angle. |
| PITCH_ANGLE11+ | "HwMnotePitchAngle" | Read/Write capability: read-only Pitch angle. |
| PHYSICAL_APERTURE 10+ | "HwMnotePhysicalAperture" | Read/Write capability: read-only Physical aperture. |
| FOCUS_MODE11+ | "HwMnoteFocusMode" | Read/Write capability: read-only Focus mode. |
| USER_COMMENT 10+ | "UserComment" | Read/Write capability: readable and writable User comments. |
| SUBSEC_TIME 12+ | "SubsecTime" | Read/Write capability: readable and writable Tag used to record fractions of seconds for the DateTime tag. |
| SUBSEC_TIME_ORIGINAL 12+ | "SubsecTimeOriginal" | Read/Write capability: readable and writable Tag used to record fractions of seconds for the DateTimeOriginal tag. |
| SUBSEC_TIME_DIGITIZED 12+ | "SubsecTimeDigitized" | Read/Write capability: readable and writable Tag used to record fractions of seconds for the DateTimeDigitized tag. |
| FLASHPIX_VERSION 12+ | "FlashpixVersion" | Read/Write capability: readable and writable FlashPix format version supported by an FPXR file. It is used to enhance device compatibility. |
| COLOR_SPACE 12+ | "ColorSpace" | Read/Write capability: readable and writable Color space information, which is usually recorded as a color space specifier. |
| PIXEL_X_DIMENSION 10+ | "PixelXDimension" | Read/Write capability: readable and writable Pixel X dimension. |
| PIXEL_Y_DIMENSION10+ | "PixelYDimension" | Read/Write capability: readable and writable Pixel Y dimension. |
| RELATED_SOUND_FILE 12+ | "RelatedSoundFile" | Read/Write capability: readable and writable Name of an audio file related to the image data. |
| FLASH_ENERGY 12+ | "FlashEnergy" | Read/Write capability: readable and writable Strobe energy at the time the image was captured, in Beam Candle Power Seconds (BCPS). |
| SPATIAL_FREQUENCY_RESPONSE 12+ | "SpatialFrequencyResponse" | Read/Write capability: readable and writable Spatial frequency table of the camera or input device. |
| FOCAL_PLANE_X_RESOLUTION 12+ | "FocalPlaneXResolution" | Read/Write capability: readable and writable Number of pixels in the image width (X) direction per FocalPlaneResolutionUnit. |
| FOCAL_PLANE_Y_RESOLUTION 12+ | "FocalPlaneYResolution" | Read/Write capability: readable and writable Number of pixels in the image height (Y) direction per FocalPlaneResolutionUnit. |
| FOCAL_PLANE_RESOLUTION_UNIT 12+ | "FocalPlaneResolutionUnit" | Read/Write capability: readable and writable Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution. |
| SUBJECT_LOCATION 12+ | "SubjectLocation" | Read/Write capability: readable and writable Location of the main subject relative to the left edge. |
| EXPOSURE_INDEX 12+ | "ExposureIndex" | Read/Write capability: readable and writable Exposure index selected at the time the image is captured. |
| SENSING_METHOD 12+ | "SensingMethod" | Read/Write capability: readable and writable Type of the image sensor on the camera. |
| FILE_SOURCE 12+ | "FileSource" | Read/Write capability: readable and writable Image source. |
| SCENE_TYPE9+ | "SceneType" | Read/Write capability: readable and writable Type of the scene, for example, portrait, scenery, motion, and night. |
| CFA_PATTERN 12+ | "CFAPattern" | Read/Write capability: readable and writable Color Filter Array (CFA) geometric pattern of the image sensor. |
| CUSTOM_RENDERED 12+ | "CustomRendered" | Read/Write capability: readable and writable Special processing on image data. |
| EXPOSURE_MODE 12+ | "ExposureMode" | Read/Write capability: readable and writable Exposure mode set when the image was captured. |
| WHITE_BALANCE 10+ | "WhiteBalance" | Read/Write capability: readable and writable White balance. |
| DIGITAL_ZOOM_RATIO 12+ | "DigitalZoomRatio" | Read/Write capability: readable and writable Digital zoom ratio when the image was captured. |
| FOCAL_LENGTH_IN_35_MM_FILM 10+ | "FocalLengthIn35mmFilm" | Read/Write capability: readable and writable Focal length in 35mm film. |
| SCENE_CAPTURE_TYPE 12+ | "SceneCaptureType" | Read/Write capability: readable and writable Type of the scene that was captured. |
| GAIN_CONTROL 12+ | "GainControl" | Read/Write capability: readable and writable Degree of overall image gain adjustment. |
| CONTRAST 12+ | "Contrast" | Read/Write capability: readable and writable Direction of contrast processing used by the camera. |
| SATURATION 12+ | "Saturation" | Read/Write capability: readable and writable Direction of saturation processing used by the camera. |
| SHARPNESS 12+ | "Sharpness" | Read/Write capability: readable and writable Direction of sharpness processing used by the camera. |
| DEVICE_SETTING_DESCRIPTION 12+ | "DeviceSettingDescription" | Read/Write capability: readable and writable Information about the photographing conditions of a specific camera model. |
| SUBJECT_DISTANCE_RANGE 12+ | "SubjectDistanceRange" | Read/Write capability: readable and writable Distance to the subject. |
| IMAGE_UNIQUE_ID 12+ | "ImageUniqueID" | Read/Write capability: readable and writable Unique identifier assigned to each image. |
| CAMERA_OWNER_NAME 12+ | "CameraOwnerName" | Read/Write capability: readable and writable Name of the camera owner. |
| BODY_SERIAL_NUMBER 12+ | "BodySerialNumber" | Read/Write capability: readable and writable Serial number of the camera body. |
| LENS_SPECIFICATION 12+ | "LensSpecification" | Read/Write capability: readable and writable Specifications of the lens. |
| LENS_MAKE 12+ | "LensMake" | Read/Write capability: readable and writable Manufacturer of the lens. |
| LENS_MODEL 12+ | "LensModel" | Read/Write capability: readable and writable Model of the lens. |
| LENS_SERIAL_NUMBER 12+ | "LensSerialNumber" | Read/Write capability: readable and writable Serial number of the lens. |
| COMPOSITE_IMAGE 12+ | "CompositeImage" | Read/Write capability: readable and writable Whether the image is a composite image. |
| SOURCE_IMAGE_NUMBER_OF_COMPOSITE_IMAGE 12+ | "SourceImageNumberOfCompositeImage" | Read/Write capability: readable and writable Number of source images of the composite image. |
| SOURCE_EXPOSURE_TIMES_OF_COMPOSITE_IMAGE 12+ | "SourceExposureTimesOfCompositeImage" | Read/Write capability: readable and writable Exposure time of source images of the composite image. |
| GAMMA 12+ | "Gamma" | Read/Write capability: readable and writable Gamma value. |
| DNG_VERSION 12+ | "DNGVersion" | Read/Write capability: readable and writable DNG version. It encodes the DNG 4-tier version number. |
| DEFAULT_CROP_SIZE 12+ | "DefaultCropSize" | Read/Write capability: readable and writable Size of the final image area, in raw image coordinates, taking into account extra pixels around the edges of the final image. |
| GIF_LOOP_COUNT 12+ | "GIFLoopCount" | Read/Write capability: read-only Number of GIF loops. The value 0 means an infinite loop, and other values means the number of loops. |
| IS_XMAGE_SUPPORTED 12+ | "HwMnoteIsXmageSupported" | Read/Write capability: readable and writable Whether XMAGE is supported. |
| XMAGE_MODE 12+ | "HwMnoteXmageMode" | Read/Write capability: readable and writable XMAGE watermark mode. |
| XMAGE_LEFT 12+ | "HwMnoteXmageLeft" | Read/Write capability: readable and writable X1 coordinate of the watermark region. |
| XMAGE_TOP 12+ | "HwMnoteXmageTop" | Read/Write capability: readable and writable Y1 coordinate of the watermark region. |
| XMAGE_RIGHT 12+ | "HwMnoteXmageRight" | Read/Write capability: readable and writable X2 coordinate of the watermark region. |
| XMAGE_BOTTOM 12+ | "HwMnoteXmageBottom" | Read/Write capability: readable and writable Y2 coordinate of the watermark region. |
| CLOUD_ENHANCEMENT_MODE 12+ | "HwMnoteCloudEnhancementMode" | Read/Write capability: readable and writable Cloud enhancement mode. |
| WIND_SNAPSHOT_MODE 12+ | "HwMnoteWindSnapshotMode" | Read/Write capability: read-only Motion snapshot mode. |
FragmentMapPropertyKey13+
Enumerates the fragment map information.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| X_IN_ORIGINAL | "XInOriginal" | X coordinate of the upper left corner of the fragment map in the original image. |
| Y_IN_ORIGINAL | "YInOriginal" | Y coordinate of the upper left corner of the fragment map in the original image. |
| WIDTH | "FragmentImageWidth" | Width of the fragment map. |
| HEIGHT | "FragmentImageHeight" | Height of the fragment map. |
ImageFormat9+
Enumerates the image formats.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| YCBCR_422_SP | 1000 | YCBCR422 semi-planar format. |
| JPEG | 2000 | JPEG encoding format. |
ComponentType9+
Enumerates the color component types of images.
System capability: SystemCapability.Multimedia.Image.ImageReceiver
| Name | Value | Description |
|---|---|---|
| YUV_Y | 1 | Luminance component. |
| YUV_U | 2 | Chrominance component. |
| YUV_V | 3 | Chrominance component. |
| JPEG | 4 | JPEG type. |
Component9+
Describes the color components of an image.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| componentType | ComponentType | Yes | No | Color component type. |
| rowStride | number | Yes | No | Row stride. The camera preview stream data needs to be read by stride. For details, see Dual-Channel Preview (ArkTS). |
| pixelStride | number | Yes | No | Pixel stride. |
| byteBuffer | ArrayBuffer | Yes | No | Component buffer. |
DecodingDynamicRange12+
Describes the desired dynamic range of an image during decoding.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| AUTO | 0 | The image is decoded based on the format. If the image is in HDR format, it is decoded based on the HDR content; otherwise, it is decoded based on the SDR content. The image source created by calling CreateIncrementalSource is decoded into SDR content. |
| SDR | 1 | The image is decoded according to the standard dynamic range. |
| HDR | 2 | The image is decoded according to the high dynamic range. The image source created by calling CreateIncrementalSource is decoded into SDR content. |
PackingDynamicRange12+
Describes the desired dynamic range of an image during encoding.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| AUTO | 0 | Adaptive. The pixelmap is encoded based on the format. If the PixelMap is in HDR format, it is encoded based on the HDR content; otherwise, it is encoded based on the SDR content. |
| SDR | 1 | The image is decoded according to the standard dynamic range. |
HdrMetadataKey12+
Enumerates the keys of HDR metadata used by pixelmap.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| HDR_METADATA_TYPE | 0 | Metadata type used by pixelmap. |
| HDR_STATIC_METADATA | 1 | Static metadata. |
| HDR_DYNAMIC_METADATA | 2 | Dynamic metadata. |
| HDR_GAINMAP_METADATA | 3 | Metadata used by gain maps. |
HdrMetadataType12+
Enumerates the values available for HDR_METADATA_TYPE in HdrMetadataKey.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| NONE | 0 | No metadata. |
| BASE | 1 | Metadata used for base graphics. |
| GAINMAP | 2 | Metadata used for gain maps. |
| ALTERNATE | 3 | Metadata used for synthesized HDR graphics. |
HdrStaticMetadata12+
Describes the static metadata keys, that is, the values available for HDR_STATIC_METADATA in HdrMetadataKey.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| displayPrimariesX | Array<number> | No | No | X coordinate of the three primary colors of the display device after normalization. The array length is 3. The unit is 0.00002. The value range is [0.0, 1.0]. |
| displayPrimariesY | Array<number> | No | No | Y coordinate of the three primary colors of the display device after normalization. The array length is 3. The unit is 0.00002. The value range is [0.0, 1.0]. |
| whitePointX | number | No | No | X coordinate of the white point after normalization. The unit is 0.00002. The value range is [0.0, 1.0]. |
| whitePointY | number | No | No | X coordinate of the white point after normalization. The unit is 0.00002. The value range is [0.0, 1.0]. |
| maxLuminance | number | No | No | Maximum luminance of the main monitor. The unit is 1, and the maximum value is 65535. |
| minLuminance | number | No | No | Minimum luminance of the main monitor. The unit is 0.0001, and the maximum value is 6.55535. |
| maxContentLightLevel | number | No | No | Maximum luminance of the displayed content. The unit is 1, and the maximum value is 65535. |
| maxFrameAverageLightLevel | number | No | No | Maximum average luminance of the displayed content. The unit is 1, and the maximum value is 65535. |
GainmapChannel12+
Describes the data content of a single channel of the gain map. For details, see ISO 21496-1.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| gainmapMax | number | No | No | Maximum value of the gain map. For details, see ISO 21496-1. |
| gainmapMin | number | No | No | Minimum value of the gain map. For details, see ISO 21496-1. |
| gamma | number | No | No | Gamma. For details, see ISO 21496-1. |
| baseOffset | number | No | No | Offset of the base graphic. For details, see ISO 21496-1. |
| alternateOffset | number | No | No | Offset of the alternative graphic that can be extracted. For details, see ISO 21496-1. |
HdrGainmapMetadata12+
Describes the metadata keys used by a gain map, that is, the values available for HDR_GAINMAP_METADATA in HdrMetadataKey. For details, see ISO 21496-1.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| writerVersion | number | No | No | Version used by the metadata editor. |
| miniVersion | number | No | No | Minimum version that needs to be understood for metadata parsing. |
| gainmapChannelCount | number | No | No | Number of color channels of the gain map. When the value is 3, the metadata values of the RGB channels are different. When the value is 1, the metadata values of the RGB channels are the same. For details, see ISO 21496-1. |
| useBaseColorFlag | boolean | No | No | Whether to use the color space of the base graphic. For details, see ISO 21496-1. |
| baseHeadroom | number | No | No | Headroom of the base graphic, which means the additional brightness that can be added to the base graphic. For details, see ISO 21496-1. |
| alternateHeadroom | number | No | No | Headroom of the alternate graphic. For details, see ISO 21496-1. |
| channels | Array<GainmapChannel> | No | No | Number of channels. The length is 3. For details, see ISO 21496-1. |
HdrMetadataValue12+
type HdrMetadataValue = HdrMetadataType | HdrStaticMetadata | ArrayBuffer | HdrGainmapMetadata
Describes the HDR metadata values used by a PixelMap, which corresponds to the values available for HdrMetadataKey.
System capability: SystemCapability.Multimedia.Image.Core
| Type | Description |
|---|---|
| HdrMetadataType | Metadata value corresponding to the HDR_GAINMAP_METADATA key in HdrMetadataKey. |
| HdrStaticMetadata | Metadata value corresponding to the HDR_STATIC_METADATA key in HdrMetadataKey. |
| ArrayBuffer | Metadata value corresponding to the HDR_DYNAMIC_METADATA key in HdrMetadataKey. |
| HdrGainmapMetadata | Metadata value corresponding to the HDR_GAINMAP_METADATA key in HdrMetadataKey. |
AntiAliasingLevel12+
Enumerates the anti-aliasing levels.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.Multimedia.Image.Core
| Name | Value | Description |
|---|---|---|
| NONE | 0 | Nearest neighbor interpolation. |
| LOW | 1 | Bilinear interpolation. |
| MEDIUM | 2 | Bilinear interpolation with mipmap enabled. You are advised to use this value when zooming out an image. |
| HIGH | 3 | Cubic interpolation. |
Supplementary Information
SVG Tags
The SVG tags are supported since API version 10. The used version is (SVG) 1.1. An XML declaration that starts with <?xml needs to be added to an SVG file, and the width and height of the SVG tag need to be set. Currently, the following tags are supported:
- a
- circla
- clipPath
- defs
- ellipse
- feBlend
- feColorMatrix
- feComposite
- feDiffuseLighting
- feDisplacementMap
- feDistantLight
- feFlood
- feGaussianBlur
- feImage
- feMorphology
- feOffset
- fePointLight
- feSpecularLighting
- feSpotLight
- feTurbulence
- filter
- g
- image
- line
- linearGradient
- mask
- path
- pattern
- polygon
- polyline
- radialGradient
- rect
- stop
- svg
- text
- textPath
- tspan
- use