openharmony 鸿蒙 arkts-apis-image-ExifMetadata

2026-08-25 浏览 (1)

Class (ExifMetadata)

ExifMetadata implements Metadata

Exchangeable Image File Format (Exif) metadata.

NOTE

The initial APIs of this module are supported since API version 23. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

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

Attribute

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

For details about the property values, see PropertyKey.

NameTypeRead-OnlyOptionalDescription
newSubfileTypenumberNoYesData type of a subfile (for example, basic types such as text or image, rather than specific storage formats).
subfileTypenumberNoYesData type of a subfile. It has been deprecated. Use newSubfileType instead.
imageWidthnumberNoYesImage width. The unit is px.
imageLengthnumberNoYesImage length. The unit is px.
bitsPerSamplenumber[]NoYesNumber of bits for each pixel component. For example, RGB has 3 components with a format of 8,8,8.
compressionnumberNoYesAlgorithm standard for image compression.
photometricInterpretationnumberNoYesPixel composition, such as RGB (Red, Green, Blue) and YCbCr (Luma, Blue-difference Chroma, Red-difference Chroma).
imageDescriptionstringNoYesImage description.
makestringNoYesManufacturer name of the capture device.
modelstringNoYesCamera model.
stripOffsetsnumber[]NoYesStrip storage offset of the image data, in bytes.
To improve the efficiency of large image access, the original pixel data is divided into multiple contiguous blocks (called strips).
This property stores the starting offset of each strip in the file sequentially.
orientationOrientationNoYesImage orientation.
samplesPerPixelnumberNoYesNumber of color components per pixel, applicable to RGB and YCbCr color models.
Since both the models are three-component models (three color channels, or one luminance component plus two chroma components), the standard value for this property is 3.
For JPEG-compressed images, this property will be replaced by the corresponding JPEG marker.
rowsPerStripnumberNoYesNumber of rows per image strip.
stripByteCountsnumber[]NoYesNumber of bytes in each strip after compression.
xResolutionnumberNoYesImage resolution in the width direction.
yResolutionnumberNoYesImage resolution in the height direction.
planarConfigurationnumberNoYesWhether the pixel components are recorded in chunked or planar format.
resolutionUnitnumberNoYesUnit of the image resolution in the width and height directions.
transferFunctionstringNoYesTransfer function for the image, which is usually used for color correction.
softwarestringNoYesName and version number of the software used to create the image.
dateTimestringNoYesDate and time when the image is created.
In this standard, it refers to the file date and time. The value format is YYYY:MM:DD HH:MM:SS (24-hour clock). For example, 2025:12:15 18:44:59.
artiststringNoYesName of the person who creates the image.
whitePointnumber[]NoYesChromaticity of the image white point.
primaryChromaticitiesnumber[]NoYesChromaticity of the image primaries.
photoModenumberNoYesImage mode.
jpegInterchangeFormatnumberNoYesStart of Image (SOI) marker of the JPEG bitstream in interchange format.
jpegInterchangeFormatLengthnumberNoYesNumber of bytes in the JPEG stream.
yCbCrCoefficientsnumber[]NoYesTransformation matrix coefficients for converting RGB image data to YCbCr image data.
yCbCrSubSamplingnumber[]NoYesSampling ratios of the chroma components and luminance component.
yCbCrPositioningnumberNoYesPosition of chroma components relative to the luminance component.
referenceBlackWhitenumber[]NoYesReference black point value and white point value.
copyrightstringNoYesCopyright notice of the image.
exposureTimenumberNoYesExposure time, in seconds.
fNumbernumberNoYesF number, for example, f/1.8.
exposureProgramnumberNoYesClass used for exposure setting when the camera captures a photo.
spectralSensitivitystringNoYesSpectral sensitivity of each channel of the camera.
gpsVersionIDnumber[]NoYesGPS information format version identifier.
gpsLatitudeRefstringNoYesGPS latitude reference. For example, N indicates north latitude, and S indicates south latitude.
gpsLatitudenumber[]NoYesGPS latitude.
The latitude is represented by three RATIONAL values (numeric values stored in fractional form), corresponding to degrees, minutes, and seconds, in the dd/1, mm/1, ss/1 format.
When using degrees and minutes, the minutes are stored with up to two decimal places, in the dd/1, mmmm/100, 0/1 format.
gpsLongitudeRefstringNoYesGPS longitude reference. For example, E indicates east longitude, and W indicates west longitude.
gpsLongitudenumber[]NoYesGPS longitude.
The longitude is represented by three RATIONAL values (numeric values stored in fractional form), corresponding to degrees, minutes, and seconds, in the dd/1, mm/1, ss/1 format.
When using degrees and minutes, the minutes are stored with up to two decimal places, in the dd/1, mmmm/100, 0/1 format.
gpsAltitudeRefnumberNoYesGPS altitude reference.
gpsAltitudenumberNoYesGPS altitude based on GPSAltitudeRef.
gpsTimestampnumber[]NoYesGPS timestamp.
gpsSatellitesstringNoYesGPS satellite used for measurement. Generally, the value is the GPS satellite's pseudo-random noise (PRN) number.
gpsStatusstringNoYesStatus of the GPS receiver when the image is recorded.
gpsMeasureModestringNoYesGPS measurement mode.
gpsDopnumberNoYesDilution of Precision (DOP) of the GPS data.
gpsSpeedRefstringNoYesSpeed unit of the GPS receiver.
gpsSpeednumberNoYesSpeed of the GPS receiver.
gpsTrackRefstringNoYesReference for the GPS receiver movement direction.
gpsTracknumberNoYesMovement direction of the GPS receiver.
gpsImgDirectionRefstringNoYesReference of the image orientation.
gpsImgDirectionnumberNoYesImage orientation at the time of capture.
gpsMapDatumstringNoYesGeodetic data used by the GPS receiver.
gpsDestLatitudeRefstringNoYesLatitude reference of the destination.
gpsDestLatitudenumber[]NoYesLatitude of the destination.
gpsDestLongitudeRefstringNoYesLongitude reference of the destination.
gpsDestLongitudenumber[]NoYesLongitude of the destination.
gpsDestBearingRefstringNoYesBearing reference to the destination.
gpsDestBearingnumberNoYesBearing to the destination.
gpsDestDistanceRefstringNoYesUnit used to express the distance to the destination.
gpsDestDistancenumberNoYesDistance to the destination.
gpsProcessingMethodstringNoYesName of the positioning method.
gpsAreaInformationstringNoYesString of the GPS area name.
gpsDateStampstringNoYesGPS date stamp.
gpsDifferentialnumberNoYesWhether differential correction has been applied to the GPS data, which is crucial for precise positioning accuracy.
gpsHPositioningErrornumberNoYesHorizontal positioning error, in meters.
isoSpeedRatingsnumberNoYesISO speed and latitude of the camera or input device, which are specified in ISO 12232.
photographicSensitivitynumber[]NoYesSensitivity of the camera or input device during image capture.
oecfArrayBufferNoYesOpto-Electric Conversion Function (OECF) specified in ISO 14524.
sensitivityTypenumberNoYesSensitivity type.
standardOutputSensitivitynumberNoYesStandard output sensitivity.
recommendedExposureIndexnumberNoYesGPS measurement mode.
isoSpeedLatitudeyyynumberNoYesMaximum dynamic range recordable by the camera sensor in a single exposure. The unit is EV.
isoSpeedLatitudezzznumberNoYesHighlight retention capacity of the camera sensor in overexposure. The unit is EV.
exifVersionstringNoYesVersion of the supported Exif standard.
dateTimeOriginalstringNoYesDate and time when the original image data is generated.
For a digital still camera (DSC), the date and time when a photo is taken are recorded. The value format is YYYY:MM:DD HH:MM:SS (24-hour clock).
dateTimeDigitizedstringNoYesDate and time when the image is stored as digital data.
For example, if a DSC captures an image and records the file at the same time, the values of DateTimeOriginal and DateTimeDigitized are the same. The value format is YYYY:MM:DD HH:MM:SS (24-hour clock).
offsetTimestringNoYesSupplement to DateTime, which resolves the timestamp ambiguity caused by geographical time zone changes.
offsetTimeOriginalstringNoYesGeographical time zone of the device.
offsetTimeDigitizedstringNoYesCoordinated Universal Time (UTC) offset at the time of image digitization, which helps to precisely adjust the timestamp.
componentsConfigurationstringNoYesInformation about the compressed data.
compressedBitsPerPixelnumberNoYesImage compression scheme. The unit is bit/pixel.
shutterSpeedValuenumberNoYesShutter speed, expressed as an Additive System of Photographic Exposure (APEX) value.
apertureValuenumberNoYesLens aperture. The unit is APEX.
brightnessValuenumberNoYesImage brightness. The unit is APEX.
exposureBiasValuenumberNoYesExposure bias.
maxApertureValuenumberNoYesMinimum aperture value of the lens.
subjectDistancenumberNoYesDistance from the capture device to the photographed object, in meters.
meteringModenumberNoYesMetering mode.
lightSourcenumberNoYesLight source.
flashnumberNoYesFlash.
focalLengthnumberNoYesFocal length of the lens, in milliseconds.
subjectAreanumber[]NoYesLocation and area of the main object in the entire scene.
makerNoteArrayBufferNoYesInformation required by the Exif/Design rule for Camera File system (DCF) writer manufacturer.
userCommentstringNoYesUser comments.
subsecTimestringNoYesSecond fraction of DateTime.
subsecTimeOriginalstringNoYesSecond of DateTimeOriginal.
subsecTimeDigitizedstringNoYesSecond of DateTimeDigitized.
flashpixVersionstringNoYesFlashPix format version supported by the FlashPix Extension Resource (FPXR), which is used to enhance device compatibility.
colorSpacenumberNoYesColor space information, which is usually recorded as a color space descriptor.
pixelXDimensionnumberNoYesImage size on the X axis (horizontal axis in a two-dimensional coordinate system). The unit is px.
pixelYDimensionnumberNoYesImage size on the Y axis (vertical axis in a two-dimensional coordinate system). The unit is px.
relatedSoundFilestringNoYesName of the audio file related to the image data.
flashEnergynumberNoYesFlash energy at the time the image is captured. The unit is beam candlepower seconds (BCPS).
spatialFrequencyResponseArrayBufferNoYesSpatial frequency table of the camera or input device.
focalPlaneXResolutionnumberNoYesNumber of pixels per unit physical length in the X-axis of the sensor's physical plane.
focalPlaneYResolutionnumberNoYesNumber of pixels per unit physical length in the Y-axis of the sensor's physical plane.
focalPlaneResolutionUnitnumberNoYesMeasurement unit of FocalPlaneXResolution and FocalPlaneYResolution.
subjectLocationnumber[]NoYesPixel coordinates of the primary object in the image (based on the origin in the upper left corner).
exposureIndexnumberNoYesExposure index selected at the time the image is captured.
sensingMethodnumberNoYesType of the image sensor on the camera.
fileSourceArrayBufferNoYesImage source.
sceneTypeArrayBufferNoYesScene type.
cfaPatternArrayBufferNoYesColor filter array (CFA) geometric pattern of the image sensor.
customRenderednumberNoYesSpecial processing of image data, such as HDR composition and AI scene enhancement.
exposureModenumberNoYesExposure mode.
whiteBalancenumberNoYesWhite balance.
digitalZoomRationumberNoYesDigital zoom ratio used when the image is captured.
focalLengthIn35mmFilmnumberNoYes35 mm equivalent focal length, in milliseconds.
sceneCaptureTypenumberNoYesType of the scene that is captured.
gainControlnumberNoYesDegree of overall image gain adjustment.
contrastnumberNoYesContrast optimization policy applied by the camera. For example, standard processing and contrast reduction.
saturationnumberNoYesColor saturation adjustment policy applied by the camera. For example, standard processing and saturation reduction.
sharpnessnumberNoYesEdge enhancement processing method applied by the camera. For example, weak sharpening and standard sharpening.
deviceSettingDescriptionArrayBufferNoYesCapture condition information of a specific camera model.
subjectDistanceRangenumberNoYesDistance range to the object.
imageUniqueIdstringNoYesUnique ID assigned to each image.
cameraOwnerNamestringNoYesName of the camera owner.
bodySerialNumberstringNoYesSerial number of the camera body.
lensSpecificationnumber[]NoYesSpecifications of the lens.
lensMakestringNoYesManufacturer of the lens.
lensModelstringNoYesModel of the lens.
lensSerialNumberstringNoYesSerial number of the lens.
compositeImagenumberNoYesWhether the image is a composite image.
sourceImageNumberOfCompositeImagenumber[]NoYesNumber of source images of the composite image.
sourceExposureTimesOfCompositeImageArrayBufferNoYesExposure time of source images for the composite image, for example, 1/33 s.
gammanumberNoYesGamma value of each component.

createInstance

static createInstance(): ExifMetadata

Creates an empty ExifMetadata instance.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Returns:

TypeDescription
ExifMetadataEmpty ExifMetadata instance.

Example:

async function exifMetadataCreateInstance(context: Context) {
  let exifMetadata = image.ExifMetadata.createInstance();
  if (exifMetadata != undefined) {
    console.info("createInstance success");
  }
}

getProperties

getProperties(key: Array<string>): Promise<Record<string, string |null>>

Obtains the property values from image metadata. This API returns the result asynchronously through a promise.

For details about the properties, see PropertyKey.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Parameters:

NameTypeMandatoryDescription
keyArray<string>YesNames of the properties to query.

Returns:

TypeDescription
Promise<Record<string, string |null>>Promise used to return the obtained image metadata property values.

Error codes:

For details about the error codes, see Image Error Codes.

Error CodeError Message
7600202Unsupported metadata. Possible causes: unsupported metadata type.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataGetProperties(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    await metaData.exifMetadata.getProperties(["ImageWidth", "ImageLength"]).then((data) => {
      console.info('Get properties ',JSON.stringify(data));
    }).catch((error: BusinessError) => {
      console.error(`Get properties failed error.code is ${error.code}, error.message is ${error.message}`);
    });
  } else {
    console.error('Metadata is null.');
  }
}

setProperties

setProperties(records: Record<string, string |null>): Promise<void>

Sets the values of specified properties in image metadata in batches. This API returns the result asynchronously through a promise.

For details about the properties, see PropertyKey.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Parameters:

NameTypeMandatoryDescription
recordsRecord<string, string |null>YesSet of key-value pairs representing properties and corresponding values of the ExifMetadata object.

Returns:

TypeDescription
Promise<void>Promise that returns no value.

Error codes:

For details about the error codes, see Image Error Codes.

Error CodeError Message
7600202Unsupported metadata. Possible causes: unsupported metadata type.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataSetProperties(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    let setkey: Record<string, string|null> = {
      "ImageWidth": "200",
      "ImageLength": "300"
    };
    await metaData.exifMetadata.setProperties(setkey).then(async () => {
      console.info('Set properties success.');
    }).catch((error: BusinessError) => {
      console.error(`Failed to set metadata Properties. code is ${error.code}, message is ${error.message}`);
    })
  } else {
    console.error('metadata is null. ');
  }
}

getAllProperties

getAllProperties(): Promise<Record<string, string |null>>

Obtains all properties and their values from the image metadata. This API returns the result asynchronously through a promise.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Returns:

TypeDescription
Promise<Record<string, string |null>>Promise used to return the values of all properties.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataGetAllProperties(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    await metaData.exifMetadata.getAllProperties().then((data) => {
      const count = Object.keys(data).length;
      console.info('Metadata have ', count, ' properties');
      console.info(`Get metadata all properties: ${data}`);
    }).catch((error: BusinessError) => {
      console.error(`Get metadata all properties failed error.code is ${error.code}, error.message is ${error.message}`);
    });
  } else {
    console.error('Metadata is null.');
  }
}

clone

clone(): Promise<ExifMetadata>

Clones the Exif metadata. This API returns the result asynchronously through a promise.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Returns:

TypeDescription
Promise<ExifMetadata>Promise used to return the Exif metadata instance if the operation is successful.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataClone(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    let new_metadata = await metaData.exifMetadata.clone();
    new_metadata.getProperties(["ImageWidth"]).then((data1) => {
      console.info(`Clone new_metadata and get Properties: ${data1}`);
    }).catch((err: BusinessError) => {
      console.error(`Clone new_metadata failed, error : ${err}`);
    });
  } else {
    console.error('Metadata is null.');
  }
}

getBlob

getBlob(): Promise<ArrayBuffer>

Obtains the metadata in binary format. This API returns the result asynchronously through a promise.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Returns:

TypeDescription
Promise<ArrayBuffer>Promise used to return the binary data of the metadata.

Example:

import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataGetBlob(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    let blob = await metaData.exifMetadata.getBlob();
    if (blob != undefined) {
      console.info("get blob success");
    }
  }
}

setBlob

setBlob(blob: ArrayBuffer): Promise<void>

Replaces the current metadata with binary data. This API returns the result asynchronously through a promise.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Image.Core

Parameters:

NameTypeMandatoryDescription
blobArrayBufferYesBinary data used to replace the metadata.

Returns:

TypeDescription
Promise<void>Promise that returns no value.

Error codes:

For details about the error codes, see Image Error Codes.

Error CodeError Message
7600206Invalid parameter. Possible causes: The blob is empty or has a length of 0.

Example:

import { fileIo } from '@kit.CoreFileKit';

function getFileFd(context: Context): number|undefined {
  const filePath: string = context.cacheDir + '/exif.jpg';  // An image containing Exif metadata is required.
  const file: fileIo.File = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
  const fd: number = file?.fd;
  return fd;
}

async function exifMetadataSetBlob(context: Context) {
  let fd = getFileFd(context);
  let imageSource = image.createImageSource(fd);
  let metaData = await imageSource.readImageMetadata(["ImageWidth", "ImageLength"]);
  if (metaData != undefined && metaData.exifMetadata != undefined) {
    let blob = await metaData.exifMetadata.getBlob();
    if (blob != undefined) {
      console.info("get blob success");
      metaData.exifMetadata.setBlob(blob);
    }
    let new_blob = metaData.exifMetadata.getBlob();
    if (new_blob != undefined) {
      console.info("new_blob is not undefined");
    }
  }
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 capi-image-nativemodule-oh-pixelmap-hdrmetadatavalue

openharmony 鸿蒙 capi-image-imagepacker-opts-

openharmony 鸿蒙 capi-image-nativemodule-image-region

openharmony 鸿蒙 capi-image-imagepacker-native-

openharmony 鸿蒙 capi-image-imagenative-

openharmony 鸿蒙 capi-image-processing-h

openharmony 鸿蒙 capi-image-ohosimagesourcesupportedformat

openharmony 鸿蒙 capi-image-nativemodule-image-size

openharmony 鸿蒙 capi-image-mdk-h

openharmony 鸿蒙 capi-image-ohosimagesourcedelaytimelist

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/r1FRhiFc