Bladeren bron

新增保存图片工具类

wangcy 4 maanden geleden
bovenliggende
commit
dab96616a1
2 gewijzigde bestanden met toevoegingen van 132 en 7 verwijderingen
  1. 125 0
      commons/basic/src/main/ets/utils/DownLoadFileHelper.ets
  2. 7 7
      features/user/src/main/ets/views/Mine.ets

+ 125 - 0
commons/basic/src/main/ets/utils/DownLoadFileHelper.ets

@@ -0,0 +1,125 @@
+import axios, { AxiosProgressEvent } from '@ohos/axios';
+import fileIo from '@ohos.file.fs';
+import { util } from '@kit.ArkTS';
+import { fileUri } from '@kit.CoreFileKit';
+import { photoAccessHelper } from '@kit.MediaLibraryKit';
+import { image } from '@kit.ImageKit';
+import { BusinessError, emitter } from '@kit.BasicServicesKit';
+import { YTLog } from '../../../../Index';
+
+export class DownLoadFileHelper {
+  private cashPaths: string[] = []
+  private currentIndex: number = 0
+
+  //传入需要下载得url数组并下载文件,通过回调函数返回对应cashPaths数组
+  async loadFiles(urls: string[], finishDownLoad: (cashPaths: string[]) => void) {
+    let filePath = getContext(this).cacheDir + '/' + util.generateRandomUUID() + '.jpg'
+    // Download the file. If the file already exists, delete the existing one first.
+    try {
+      fileIo.accessSync(filePath);
+      fileIo.unlinkSync(filePath);
+    } catch (err) {
+    }
+
+    await axios({
+      url: urls[this.currentIndex],
+      method: 'get',
+      context: getContext(this),
+      filePath: filePath,
+      onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
+        // console.info("progress: " + progressEvent && progressEvent.loaded && progressEvent.total ?
+        // Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
+      }
+    })
+    this.currentIndex++
+    this.cashPaths.unshift(filePath)
+    if (this.currentIndex < urls.length) {
+      this.loadFiles(urls, finishDownLoad)
+    } else {
+      finishDownLoad(this.cashPaths)
+    }
+  }
+
+  //传入需要保存得cashPaths数组,并通过ShowAssetsCreationDialog保存文件
+  async saveByShowAssetsCreationDialog(cashPaths: string[], context: Context, success?: () => void) {
+    const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
+    const uris = cashPaths.map(item => fileUri.getUriFromPath(item))
+    try {
+      // 指定待保存照片的创建选项,包括文件后缀和照片类型,标题和照片子类型可选。
+      const photoCreationConfigs = uris.map(() => {
+        const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
+          fileNameExtension: 'jpg',
+          photoType: photoAccessHelper.PhotoType.IMAGE,
+        }
+        return photoCreationConfig
+      })
+      // 基于弹窗授权的方式获取媒体库的目标uri。
+      let desFileUris: Array<string> =
+        await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfigs);
+
+      let index = 0
+      while (index < uris.length) {
+        //通过该uri打开图片
+        let file = await fileIo.open(desFileUris[index], fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
+        //获取流
+        const buffer = await this.getFileBuffer(cashPaths[index])
+        //通过流写入相册
+        let writeLen = await fileIo.write(file.fd, buffer)
+        //关流
+        await fileIo.close(file)
+        index++
+      }
+      success?.()
+    } catch (err) {
+      emitter.emit('hide')
+    }
+  }
+
+  //传入图片地址,转化为流
+  async getFileBuffer(filePath: string): Promise<ArrayBuffer> {
+    try {
+      const imageSource = image.createImageSource(filePath)
+      let imagePackerApi = image.createImagePacker();
+      let buffer = await imagePackerApi.packing(imageSource, {
+        quality: 100,
+        format: 'image/jpeg'
+      })
+      return buffer
+    } catch (err) {
+      let error: BusinessError = err as BusinessError;
+      console.error(`read file failed, errCode:${error.code}, errMessage:${error.message}`);
+      return Promise.reject(err)
+    }
+  }
+
+  //须先申请权限ohos.permission.WRITE_IMAGEVIDEO
+  async saveImgToAssets(cashPaths: string[]) {
+    try {
+      let index = 0;
+      while (index < cashPaths.length) {
+        //获取当前上下文
+        //通过accessHelper模块获取accessHelper对象
+        let accessHelper = photoAccessHelper.getPhotoAccessHelper(getContext())
+        //指定待创建的文件类型、后缀和创建选项,创建图片或视频资源 返回创建的图片和视频的uri
+        let uri = await accessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
+        //通过该uri打开图片
+        let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
+        //获取流
+        const buffer = await this.getFileBuffer(cashPaths[index])
+        //通过流写入相册
+        let writeLen = await fileIo.write(file.fd, buffer)
+        //关流
+        await fileIo.close(file)
+        index++
+      }
+
+    } catch (e) {
+      YTLog.error(e)
+    }
+  }
+
+
+  getType(imgUrl: string) {
+    return imgUrl.split('.').pop()
+  }
+}

+ 7 - 7
products/entry/src/main/ets/views/Mine.ets → features/user/src/main/ets/views/Mine.ets

@@ -19,7 +19,7 @@ export struct Mine {
         }
 
       },
-      src: $r('[user].media.right_arrow')
+      src: $r('app.media.right_arrow')
     },
     {
       text: '给个好评',
@@ -37,14 +37,14 @@ export struct Mine {
           IBestToast.show('出现未知错误,请稍后再试')
         });
       },
-      src: $r('[user].media.right_arrow')
+      src: $r('app.media.right_arrow')
     },
     {
       text: '关于我们',
       click: () => {
         yTRouter.router2AboutUS()
       },
-      src: $r('[user].media.right_arrow')
+      src: $r('app.media.right_arrow')
     }
   ]
 
@@ -63,7 +63,7 @@ export struct Mine {
               .borderRadius(20)
               .margin({ right: 9 })
           } else {
-            Image($r('[user].media.app_icon'))
+            Image($r('app.media.app_icon'))
               .height(40)
               .aspectRatio(1)
               .margin({ right: 9 })
@@ -76,7 +76,7 @@ export struct Mine {
               .fontColor('#FF000000')
             Text() {
               Span('ID:' + (this.userInfo.getId()?.toString().padStart(8, '0') ?? '00000000'))
-              ImageSpan($r('[user].media.copy'))
+              ImageSpan($r('app.media.copy'))
                 .width(7)
                 .height(8)
                 .margin({ left: 4 })
@@ -116,12 +116,12 @@ export struct Mine {
                   Text(this.userInfo.getAiNum()?.toString() ?? '')
                     .fontWeight(600)
                     .fontSize($r('[basic].float.page_text_font_size_14'))
-                  Image($r('[user].media.right_arrow'))
+                  Image($r('app.media.right_arrow'))
                     .width(24)
                     .aspectRatio(1)
                 }
               } else {
-                Image($r('[user].media.right_arrow'))
+                Image($r('app.media.right_arrow'))
                   .width(24)
                   .aspectRatio(1)
               }