YTPhotoHelper.ets 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import axios, { AxiosProgressEvent } from '@ohos/axios';
  2. import { fileIo, fileUri } from '@kit.CoreFileKit';
  3. import { camera, cameraPicker as picker } from '@kit.CameraKit';
  4. import { util } from '@kit.ArkTS';
  5. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  6. import { image } from '@kit.ImageKit';
  7. import { BusinessError } from '@kit.BasicServicesKit';
  8. import { YTLog } from '../../../../Index';
  9. /**
  10. * @method cashPhotos 传入需要下载得url数组并下载文件,通过回调函数返回对应cashPaths数组
  11. * @method takePicture 拍照获取图片
  12. * @method selectImage 从相册选择图片
  13. * @method saveByShowAssetsCreationDialog 通过ShowAssetsCreationDialog保存文件(弹窗)
  14. * @method getPhotoFileBuffer 将缓存的图片转化为流
  15. * @method saveImgToAssets 直接保存图片至相册 需要权限
  16. */
  17. export class YTPhotoHelper {
  18. private cashPaths: string[] = []
  19. private currentIndex: number = 0
  20. private readonly context: Context
  21. constructor(context: Context) {
  22. this.context = context
  23. }
  24. //传入需要下载得url数组并下载文件,通过回调函数返回对应cashPaths数组
  25. async cashPhotos(urls: string[], finishDownLoad: (cashPaths: string[]) => void, cashPhotoType: string = '.jpg') {
  26. let filePath = this.context.cacheDir + '/' + util.generateRandomUUID() + cashPhotoType
  27. // Download the file. If the file already exists, delete the existing one first.
  28. try {
  29. fileIo.accessSync(filePath);
  30. fileIo.unlinkSync(filePath);
  31. } catch (err) {
  32. YTLog.error(err)
  33. }
  34. await axios({
  35. url: urls[this.currentIndex],
  36. method: 'get',
  37. context: getContext(this),
  38. filePath: filePath,
  39. onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
  40. YTLog.info("progress: " + progressEvent && progressEvent.loaded && progressEvent.total ?
  41. Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
  42. }
  43. })
  44. this.currentIndex++
  45. this.cashPaths.unshift(filePath)
  46. if (this.currentIndex < urls.length) {
  47. this.cashPhotos(urls, finishDownLoad, cashPhotoType)
  48. } else {
  49. finishDownLoad(this.cashPaths)
  50. }
  51. }
  52. //拍照获取图片
  53. async takePicture() {
  54. let pathDir = this.context.filesDir;
  55. let fileName = `${new Date().getTime()}`
  56. let filePath = pathDir + `/${fileName}.png`
  57. fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);
  58. let uri = fileUri.getUriFromPath(filePath);
  59. let pickerProfile: picker.PickerProfile = {
  60. cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
  61. saveUri: uri
  62. };
  63. let result: picker.PickerResult =
  64. await picker.pick(this.context, [picker.PickerMediaType.PHOTO], //(如果需要录像可以添加) picker.PickerMediaType.VIDEO
  65. pickerProfile);
  66. if (!result.resultUri) {
  67. return Promise.reject('用户未拍照')
  68. }
  69. return filePath
  70. }
  71. //从相册选择图片
  72. selectImage(success: (fullPath: string) => void, maxNumber: number = 1) {
  73. const option = new photoAccessHelper.PhotoSelectOptions()
  74. option.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE
  75. option.maxSelectNumber = maxNumber
  76. const picker = new photoAccessHelper.PhotoViewPicker()
  77. picker.select(option)
  78. .then(res => {
  79. const photoName = util.generateRandomUUID()
  80. const photoType = '.' + res.photoUris[0].split('.').pop()
  81. const fullPath = this.context.cacheDir + '/' + photoName + photoType
  82. const photo = fileIo.openSync(res.photoUris[0])
  83. try {
  84. fileIo.copyFile(photo.fd, fullPath)
  85. .then(() => {
  86. YTLog.info(fullPath)
  87. success(fullPath)
  88. })
  89. } catch (err) {
  90. YTLog.error(err)
  91. }
  92. })
  93. }
  94. //传入需要保存得cashPaths数组,并通过ShowAssetsCreationDialog保存文件
  95. async saveByShowAssetsCreationDialog(cashPaths: string[], success?: () => void) {
  96. const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
  97. const uris = cashPaths.map(item => fileUri.getUriFromPath(item))
  98. try {
  99. // 指定待保存照片的创建选项,包括文件后缀和照片类型,标题和照片子类型可选。
  100. const photoCreationConfigs = uris.map(() => {
  101. const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
  102. fileNameExtension: 'jpg',
  103. photoType: photoAccessHelper.PhotoType.IMAGE,
  104. }
  105. return photoCreationConfig
  106. })
  107. // 基于弹窗授权的方式获取媒体库的目标uri。
  108. let desFileUris: Array<string> =
  109. await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfigs);
  110. let index = 0
  111. while (index < uris.length) {
  112. //通过该uri打开图片
  113. let file = await fileIo.open(desFileUris[index], fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  114. //获取流
  115. const buffer = await this.getPhotoFileBuffer(cashPaths[index])
  116. //通过流写入相册
  117. await fileIo.write(file.fd, buffer)
  118. //关流
  119. await fileIo.close(file)
  120. index++
  121. }
  122. success?.()
  123. } catch (err) {
  124. YTLog.error(err)
  125. }
  126. }
  127. //传入图片地址,转化为流
  128. async getPhotoFileBuffer(filePath: string): Promise<ArrayBuffer> {
  129. try {
  130. const imageSource = image.createImageSource(filePath)
  131. let imagePackerApi = image.createImagePacker();
  132. let buffer = await imagePackerApi.packing(imageSource, {
  133. quality: 100,
  134. format: 'image/jpeg'
  135. })
  136. return buffer
  137. } catch (err) {
  138. let error: BusinessError = err as BusinessError;
  139. console.error(`read file failed, errCode:${error.code}, errMessage:${error.message}`);
  140. return Promise.reject(err)
  141. }
  142. }
  143. //须先申请权限ohos.permission.WRITE_IMAGEVIDEO 保存图片至相册
  144. async saveImgToAssets(cashPaths: string[]) {
  145. try {
  146. let index = 0;
  147. while (index < cashPaths.length) {
  148. //获取当前上下文
  149. //通过accessHelper模块获取accessHelper对象
  150. let accessHelper = photoAccessHelper.getPhotoAccessHelper(getContext())
  151. //指定待创建的文件类型、后缀和创建选项,创建图片或视频资源 返回创建的图片和视频的uri
  152. let uri = await accessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
  153. //通过该uri打开图片
  154. let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  155. //获取流
  156. const buffer = await this.getPhotoFileBuffer(cashPaths[index])
  157. //通过流写入相册
  158. await fileIo.write(file.fd, buffer)
  159. //关流
  160. await fileIo.close(file)
  161. index++
  162. }
  163. } catch (e) {
  164. YTLog.error(e)
  165. }
  166. }
  167. }