目录

读取和编辑图片Exif信息

Image Kit提供图片Exif信息的读取与编辑能力。

Exif(Exchangeable image file format)是专门为数码相机的照片设定的文件格式,可以记录数码照片的属性信息和拍摄数据。需要图片包含Exif信息。

在图库、相机、图片编辑等应用中,开发者可以读取图片的拍摄时间、方向、焦距、地理位置等Exif信息,也可以在需要时修改部分Exif信息。例如,当摄像机的手动镜头参数无法自动写入Exif信息,或者因相机断电导致拍摄时间错误时,可手动修正对应的Exif数据。

系统目前仅支持读取和修改部分Exif信息,具体支持范围请参见PropertyKey。不同图片格式对Exif信息的读写支持情况如下。

图片格式 读取Exif信息 修改Exif信息
JPG/JPEG 支持 支持
PNG 支持 支持
HEIF 支持 支持
WebP23+ 支持 支持
DNG23+ 支持 不支持

接口说明

Exif信息的读取与编辑相关的API如下,详细介绍请参考ImageSource。

接口 说明
getImageProperty 获取指定属性键的Exif信息。
modifyImageProperty 修改指定属性键的Exif信息。

注意事项

开发步骤

获取图片并创建ImageSource对象后,可读取或编辑Exif信息。示例代码如下:

  1. 导入相关模块包。

    // 导入相关模块。
    import { image } from '@kit.ImageKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. 获取指定属性键的Exif信息。

    // 获取指定key的Exif信息接口示例
    async getExif(imageSourceApi: image.ImageSource | undefined, key: image.PropertyKey): Promise<string> {
      let info: string = '';
      if (imageSourceApi) {
        console.info('getExif: The imageSourceApi is not undefined.');
        // 根据传入的key获取其Exif信息
        let options: image.ImagePropertyOptions = { index: 0, defaultValue: 'This key has no value!' };
        try {
          let data = await imageSourceApi.getImageProperty(key, options);
          info = `Succeeded in getting the ${key}'s value: ${data}.`;
          console.info(info);
          return info; // 获取key值成功时返回获取到的key值
        } catch (error) {
          info =
            `Failed to get the value of the ${key} with error: ${error}.`;
          console.error(info);
          return info; // 获取key值失败时返回错误信息
        }
      } else {
        info = 'getExif: The imageSourceApi is undefined.';
        console.info(info);
        return info; // 如果 imageSourceApi 是 undefined,则直接返回信息
      }
    }
  3. 修改指定属性键的Exif信息。

    // 修改指定key的Exif信息的接口示例
    async modifyExif(imageSourceApi: image.ImageSource | undefined, key: image.PropertyKey, value: string)
      : Promise<string> {
      let info: string = '';
      if (imageSourceApi) {
        // 编辑Exif信息
        try {
          await imageSourceApi.modifyImageProperty(key, value);
          try {
            let modifyValue = await imageSourceApi.getImageProperty(key)
            info = `The ${key}'s value is modified to ${modifyValue}.`
            console.info(info);
            return info; // 获取key值成功时返回修改成功信息
          } catch (error) {
            console.error(`Failed to get the ${key}'s value with ${error}`);
            console.error(info);
            return info; // 获取key值失败时返回错误信息
          }
        } catch (error) {
          info = `Failed to modify the ${key}'s value with ${error}`;
          console.error(info);
          return info; // 修改key值失败时返回错误信息
        }
      } else {
        info = 'modifyExif: The imageSourceApi is undefined.';
        console.info(info);
        return info; // 如果 imageSourceApi 是 undefined,直接返回信息
      }
    }