HarmonyOS 从图库获取图片后,如何计算该图片的md5(16位字符串)?

let photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = maxSelectNumber;
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
  console.info('PhotoViewPicker.select successfully, photoSelectResult uri: ' + JSON.stringify(photoSelectResult));
  onSuccess(photoSelectResult)
}).catch((err: BusinessError) => {
  console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
  onError(err)
});

获取图库图片后,拿到图片uri,如何计算图片md5值?

阅读 523
1 个回答

请参考以下demo:

import common from '@ohos.app.ability.common';
import picker from '@ohos.file.picker';
import { BusinessError } from '@kit.BasicServicesKit';
import Hash from '@ohos.file.hash';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Index {
  @State message: string = 'hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            let context = getContext(this) as common.Context; // 请确保 getContext(this) 返回结果为 UIAbilityContext
            let photoSelectOptions = new picker.PhotoSelectOptions();
            photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
            photoSelectOptions.maxSelectNumber = 1;
            let photoPicker = new picker.PhotoViewPicker();
            photoPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
              console.info('PhotoViewPicker.select successfully, photoSelectResult uri: ' + JSON.stringify(photoSelectResult));

              let uriString: string = photoSelectResult.photoUris[0]
              let pathDir = context.filesDir;

              let file1 = fs.openSync(uriString)
              let filePath = pathDir + '/' + file1.name
              fs.copyFileSync(file1.fd, filePath)

              console.info("calculate filePath: " + filePath);

              Hash.hash(filePath, "md5").then((str: string) => {
                console.info("calculate file hash succeed:" + str);
              }).catch((err: BusinessError) => {
                console.error("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
              });

            }).catch((err: BusinessError) => {
              console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));

            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

md5计算参考如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-hash-V5\#hashhash

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏