HarmonyOS 鸿蒙Next中悬赏50积分麻烦帮修改一下ets返回数据的输出格式

HarmonyOS 鸿蒙Next中悬赏50积分麻烦帮修改一下ets返回数据的输出格式

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { media } from '@kit.MediaKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import fs from '@ohos.file.fs';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

const TAG: string = 'ImageSegmentation';

interface photoInfo {
  title?: string
  fiename?: string
  duration?: number
  Path?: string
  Pathurl?: string
  size?: string
  byteSize?: number
  mimeType: 'video' | 'image'
  width?: number
  height?: number
  dateAddedTime?: number
}

interface SelectRes {
  ArryData?: photoInfo[]
}

export class ImagePickerUtil {
  // 使用PhotoPicker选取图片
  static async getUriGallery(): Promise<SelectRes[]> {
    return new Promise((resolve,reject)=>{
      let jsonArray: SelectRes[] = [];

      const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();

      photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;

      photoSelectOptions.maxSelectNumber = 9;

      const photoViewPicker = new photoAccessHelper.PhotoViewPicker();

      photoViewPicker.select(photoSelectOptions).then((SelectResult: photoAccessHelper.PhotoSelectResult) => {

        let PhotoFile: Promise<void>[] = []

        const Selecturi =  SelectResult.photoUris

        Selecturi.forEach(async (item)=>{
          let url = item
          PhotoFile.push(ImagePickerUtil.getPhotoInfo(url).then((photoInfo)=>{
            if(photoInfo){
              jsonArray.push({
                ArryData: [photoInfo]
              } as SelectRes)
            }
          }))
        })

        Promise.all(PhotoFile).then(()=>{
          resolve(jsonArray)
        })
      })

    })
  }


  static async getPhotoInfo(uri: string): Promise<photoInfo> {

    let context = getContext();

    let tempDir = context.tempDir;

    let photoAccess = photoAccessHelper.getPhotoAccessHelper(context);

    const predicates = new dataSharePredicates.DataSharePredicates()

    predicates.equalTo('uri', uri);

    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await photoAccess.getAssets({

      fetchColumns: [

        photoAccessHelper.PhotoKeys.TITLE,

        photoAccessHelper.PhotoKeys.DISPLAY_NAME,

        photoAccessHelper.PhotoKeys.DATE_ADDED_MS,

        photoAccessHelper.PhotoKeys.DATE_MODIFIED_MS,

        photoAccessHelper.PhotoKeys.URI,

        photoAccessHelper.PhotoKeys.PHOTO_TYPE,

        photoAccessHelper.PhotoKeys.WIDTH,

        photoAccessHelper.PhotoKeys.HEIGHT,

        photoAccessHelper.PhotoKeys.SIZE,

        photoAccessHelper.PhotoKeys.DURATION,

        photoAccessHelper.PhotoKeys.ORIENTATION

      ],

      predicates,

    } as photoAccessHelper.FetchOptions)

    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();

    const fiename = asset.get(photoAccessHelper.PhotoKeys.DISPLAY_NAME) as string

    const duration = asset.get(photoAccessHelper.PhotoKeys.DURATION) as number

    const title = asset.get(photoAccessHelper.PhotoKeys.TITLE) as string

    const byteSize = asset.get(photoAccessHelper.PhotoKeys.SIZE) as number

    const width = asset.get(photoAccessHelper.PhotoKeys.WIDTH) as number

    const height = asset.get(photoAccessHelper.PhotoKeys.HEIGHT) as number

    const photoType = asset.photoType

    const dateAddedTime = asset.get(photoAccessHelper.PhotoKeys.DATE_ADDED_MS) as number

    let Path = uri

    let tempPath = tempDir + '/' + fiename

    await ImagePickerUtil.copyFile(uri, tempPath)

    let Pathurl = tempPath

    fetchResult.close()

    await photoAccess.release()

    return {

      fiename,

      Path,

      Pathurl,

      duration,

      size: ImagePickerUtil.formatFileSize(byteSize),

      byteSize,

      width,

      height,

      title,

      mimeType: photoType === photoAccessHelper.PhotoType.VIDEO ? 'video' : 'image',

      dateAddedTime

    } as photoInfo

  }


  static async copyFile(Pathuri: string, tempPath: string) {

    let sourceFile: fs.File | null = null;

    let destFile: fs.File | null = null;

    try {

      sourceFile = fs.openSync(Pathuri, fs.OpenMode.READ_ONLY);

      destFile = fs.openSync(tempPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

      fs.copyFileSync(sourceFile.fd, destFile.fd);

    } catch (err) {

      console.log('err', err.message);

    } finally {

      if (sourceFile) {

        // console.log('sourceFile', sourceFile);

        fs.closeSync(sourceFile);

      }

      if (destFile) {

        // console.log('destFile', destFile);

        fs.closeSync(destFile);

      }

    }

  }


  static formatFileSize(bytes: number): string {

    if (bytes < 1024) {

      return bytes + ' B';

    } else if (bytes < 1024 * 1024) {

      return (bytes / 1024).toFixed(2) + ' KB';

    } else {

      return (bytes / (1024 * 1024)).toFixed(2) + ' MB';

    }

  }
}

B页面代码如下:

ImagePickerUtil.getUriGallery().then((Uridata: SelectRes[]) => {
  console.log('获取到的数据:', JSON.stringify(Uridata));
})

当前B页面输出的数据格式如下:

[{"ArryData":[{"fiename":"IMG_098.jpeg","Path":"file://media/Photo/104/IMG_1758605486_098/IMG_098.jpeg","Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_098.jpeg","duration":0,"size":"2.64 KB","byteSize":2700,"width":71,"height":71,"title":"IMG_098","mimeType":"image","dateAddedTime":1758605386859}]},{"ArryData":[{"fiename":"IMG_094.jpeg","Path":"file://media/Photo/100/IMG_1758602551_094/IMG_094.jpeg","Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_094.jpeg","duration":0,"size":"554.63 KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_094","mimeType":"image","dateAddedTime":1758602451387}]},{"ArryData":[{"fiename":"IMG_097.jpeg","Path":"file://media/Photo/103/IMG_1758602713_097/IMG_097.jpeg","Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_097.jpeg","duration":0,"size":"222.61 KB","byteSize":227955,"width":1544,"height":1432,"title":"IMG_097","mimeType":"image","dateAddedTime":1758602613751}]}]

B页面需要的正确输出数据格式为如下:

{"ArryData":[
{"fiename":"IMG_091.jpeg","Path":"file://media/Photo/10,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_091.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_091","mimeType":"image","dateAddedTime":1758602451568},{"fiename":"IMG_092.jpeg","Path":"file://media/Photo/11,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_092.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_092","mimeType":"image","dateAddedTime":1758602451568},{"fiename":"IMG_093.jpeg","Path":"file://media/Photo/10,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_093.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_093","mimeType":"image","dateAddedTime":1758602451568}
]}

更多关于HarmonyOS 鸿蒙Next中悬赏50积分麻烦帮修改一下ets返回数据的输出格式的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

楼主可以参考下修改下返回值:

export class ImagePickerUtil {
  // 使用PhotoPicker选取图片
  static async getUriGallery(): Promise<SelectRes> {
    return new Promise((resolve, reject) => {
      let jsonArray: SelectRes = {};
      let arrayData:photoInfo[] = []
      const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      photoSelectOptions.maxSelectNumber = 9;
      const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoViewPicker.select(photoSelectOptions).then((SelectResult: photoAccessHelper.PhotoSelectResult) => {
        let PhotoFile: Promise<void>[] = []
        const Selecturi = SelectResult.photoUris
        Selecturi.forEach(async (item) => {
          let url = item
          PhotoFile.push(ImagePickerUtil.getPhotoInfo(url).then((photoInfo) => {
            if (photoInfo) {
              arrayData.push(photoInfo);
            }
          }))

        })

        Promise.all(PhotoFile).then(() => {
          jsonArray.ArryData = arrayData
          resolve(jsonArray)
        })
      })
    })
  }
ImagePickerUtil.getUriGallery().then((Uridata: SelectRes) => {
  console.log('获取到的数据:', JSON.stringify(Uridata));
})

更多关于HarmonyOS 鸿蒙Next中悬赏50积分麻烦帮修改一下ets返回数据的输出格式的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


感谢,

严谨点,就这样:

ImagePickerUtil.getUriGallery().then((Uridata: SelectRes[]) => { console.log(‘获取到的数据:’, JSON.stringify(Uridata));

// 检查数组是否有数据,然后获取第一条 if (Uridata && Uridata.length > 0) { const firstItem = Uridata[0]; console.log(‘第一条数据:’, JSON.stringify(firstItem)); // 这里可以使用firstItem进行后续操作 } else { console.log(‘没有获取到数据’); } });

ImagePickerUtil.getUriGallery().then((Uridata: SelectRes[]) => {
    console.log('获取到的数据:', JSON.stringify(Uridata[0]));
})

盲写的,是这样不?

想要的是jsonObject,返回的是jsonArray,去第一条就完了, arr[0],是这个区别吗?

在HarmonyOS Next的ets文件中,使用JSON.stringify()方法格式化返回数据。示例代码:

let data = {key: "value"};
console.log(JSON.stringify(data, null, 2));

输出带缩进的JSON格式。若需自定义格式,可通过字符串模板拼接数据:

let result = `Data: ${data.key}`;
console.log(result);

使用Logger模块的JSON序列化方法也可实现结构化输出。

当前代码返回的是SelectRes[]数组格式,每个元素包含一个ArryData数组。要改为单个SelectRes对象,其中ArryData包含所有图片信息,请修改getUriGallery方法:

static async getUriGallery(): Promise<SelectRes> {
  return new Promise((resolve, reject) => {
    let photoInfos: photoInfo[] = []; // 改为单个数组存储所有图片信息

    const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber = 9;

    const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
    photoViewPicker.select(photoSelectOptions).then((SelectResult: photoAccessHelper.PhotoSelectResult) => {
      let PhotoFile: Promise<void>[] = [];
      const Selecturi = SelectResult.photoUris;

      Selecturi.forEach(async (item) => {
        PhotoFile.push(ImagePickerUtil.getPhotoInfo(item).then((photoInfo) => {
          if (photoInfo) {
            photoInfos.push(photoInfo); // 直接添加到photoInfos数组
          }
        }));
      });

      Promise.all(PhotoFile).then(() => {
        resolve({ ArryData: photoInfos } as SelectRes); // 返回单个SelectRes对象
      });
    });
  });
}

修改后,B页面调用代码保持不变,输出格式将变为所需的单个对象结构,其中ArryData数组包含所有选中的图片信息。

回到顶部