HarmonyOS 相机拍照后如何获获取图片信息(eg:宽高),上传也需要放到copy到沙盒中操作吗

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

这个是通过picker选择图片=>返回uris后获取图片信息,再用 uriGetAssets()函数处理:

import picker from '@ohos.file.picker';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { BusinessError } from '@ohos.base';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

// 定义一个uri数组,用于接收PhotoViewPicker选择图片返回的uri
let uris: Array<string> = [];
const context = getContext(this);

@Entry
@Component
struct WebComponent {


  build() {
    Column() {
      // Text($r('app.string.page_show22'))
      Button('获取图片信息')
        .onClick(() => {
          photoPickerGetUri()
          // uriGetAssets()
        })
    }
  }
}
// 调用PhotoViewPicker.select选择图片
async function photoPickerGetUri() {
  try {
    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));
      uris = PhotoSelectResult.photoUris;
      uriGetAssets(uris)
    }).catch((err: BusinessError) => {
      console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

async function uriGetAssets(uris:Array<string>) {
  try {
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    // 配置查询条件,使用PhotoViewPicker选择图片返回的uri进行查询
    predicates.equalTo('uri', uris[0]);
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: ['width','height','title'],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    // 得到uri对应的PhotoAsset对象,读取文件的部分信息
    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    console.info('asset displayName: ', asset.displayName);
    console.info('asset uri: ', asset.uri);
    console.info('asset photoType: ', asset.photoType);
    console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH));
    console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT));
    console.info('asset title: ' + asset.get(photoAccessHelper.PhotoKeys.TITLE));
    // 获取缩略图
    asset.getThumbnail((err, pixelMap) => {
      if (err == undefined) {
        console.info('getThumbnail successful ' + JSON.stringify(pixelMap));
      } else {
        console.error('getThumbnail fail', err);
      }
    });
  } catch (error){
    console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
  }
}

2.能否提供拍照后上传操作前处理的示例代码:打开图库/拍照上传,包含copy图片到缓存区。

import common from '@ohos.app.ability.common';
import { BusinessError, request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

let context = getContext(this) as common.UIAbilityContext;
//当前上传应用文件功能,仅支持上传应用缓存文件路径(cacheDir)下的文件
let cacheDir = context.cacheDir;

//图库选择图片并上传
@Entry
@Component
struct Index {
  @State uris: Array<string> = [];
  build() {
    Row() {
      Column() {

        Button('拍照并上传').onClick(() => {
          const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
          photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
          photoSelectOptions.maxSelectNumber = 1;

          const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
          //拍照或选择图片
          photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
            photoSelectResult.photoUris.forEach((uri) => {
              let fileName = uri.substring(uri.lastIndexOf('/') + 1)
              let name = fileName.substring(0, fileName.indexOf('.'))
              let type = fileName.substring(fileName.indexOf('.') + 1)
              let file = fs.openSync(uri, fs.OpenMode.CREATE);
              // 复制文件到缓存目录下
              fs.copyFileSync(file.fd, cacheDir + '/' + fileName)
              fs.closeSync(file);

              // 上传任务配置项
              let uploadConfig: request.UploadConfig = {
                url: 'https://xxx',
                header: new Map<Object, string>(),
                data: [],
                method: 'POST',
                files: [
                  { filename: fileName, name: name, uri: "internal://cache/" + fileName, type: type }
                ]
              }

              try {
                console.log('开始uploadFile');
                request.uploadFile(context, uploadConfig)
                  .then((uploadTask: request.UploadTask) => {
                    uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
                      for (let i = 0; i < taskStates.length; i++) {
                        console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
                      }
                    });
                  })
                  .catch((err: BusinessError) => {
                    console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
                  })
              } catch (error) {
                let err: BusinessError = error as BusinessError;
                console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
              }
            })
          }).catch((err: BusinessError) => {
            console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
          })
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
如何获取窗口的信息
2378浏览 • 1回复 待解决
如何获取图片,你知道
2478浏览 • 1回复 待解决
HarmonyOS photoAsset获取图片失败
397浏览 • 1回复 待解决
鸿蒙如何获取Element图片
7953浏览 • 1回复 待解决
如何获取屏幕,你知道
2493浏览 • 1回复 待解决
HarmonyOS 如何加载本地盒中的html
108浏览 • 1回复 待解决
如何获取拍照图片地址
1992浏览 • 1回复 待解决
js相机组件拍照自动保存
4193浏览 • 1回复 待解决
如何测量获取控件
843浏览 • 1回复 待解决
HarmonyOS 如何获取Webview的
57浏览 • 1回复 待解决
ArkTs如何获取组件的
4660浏览 • 1回复 待解决