HarmonyOS 鸿蒙Next showAssetsCreationDialog点击允许之后相册没有生成照片

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next showAssetsCreationDialog点击允许之后相册没有生成照片
<markdown _ngcontent-gwx-c149="" class="markdownPreContainer">

http.createHttp().request(request.url, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000
},
async (error: BusinessError, data: http.HttpResponse) => {
if (error) {

} else { if (http.ResponseCode.OK === data.responseCode) { let imageBuffer: ArrayBuffer = data.result as ArrayBuffer; try { const context = getContext(this); let helper = photoAccessHelper.getPhotoAccessHelper(context); let uri = getContext(this).tempDir + <span class="javascript">/${dayjs().valueOf()}.jpg</span> let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE) // 写入文件 await fileIo.write(file.fd, imageBuffer); // 关闭文件 await fileIo.close(file.fd);

helper.showAssetsCreationDialog([fileUri.getUriFromPath(uri)], [ { fileNameExtension: ‘jpg’, photoType: photoAccessHelper.PhotoType.IMAGE, } ]).then(() => {

}) .catch((error: BusinessError) => {

}) } catch (error) {

} } else {

} } } ) <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

</markdown>


更多关于HarmonyOS 鸿蒙Next showAssetsCreationDialog点击允许之后相册没有生成照片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

请参考以下代码:

```
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';
import { image } from '@kit.ImageKit';
import { promptAction } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { http } from '@kit.NetworkKit';
import ResponseCode from '@ohos.net.http';

@Entry @Component struct PictureSave { @State message: string = ‘Hello World’; @State imageBuffer: ArrayBuffer | undefined = undefined; // 图片ArrayBuffer @State image: PixelMap | undefined = undefined; @State photoAccessHelper: photoAccessHelper.PhotoAccessHelper | undefined = undefined;

async savePng() { console.debug(image =&gt; 保存网络图片到应用沙盒) const context = getContext(this); let dirPath = context.cacheDir let fileName = ‘temp2.jpg’ // let fileName = ‘temp1.mp4’ //防止沙箱重名导致下载失败 if (fileIo.accessSync(${dirPath}/${fileName})) { fileIo.rmdirSync(${dirPath}/${fileName}) }

<span class="hljs-keyword">try</span> {
  request.downloadFile(context, {
    enableMetered: <span class="hljs-literal">true</span>,
    url: <span class="hljs-string">"http://gips0.baidu.com/it/u=3602773692,1512483864&amp;fm=3028&amp;app=3028&amp;f=JPEG&amp;fmt=auto?w=960&amp;h=1280"</span>,
    <span class="hljs-comment">// url: "http://vjs.zencdn.net/v/oceans.mp4",</span>
    filePath: `${dirPath}/${fileName}`
  }).then((downloadTask: request.DownloadTask) =&gt; {
    downloadTask.on(<span class="hljs-string">'fail'</span>, (err: number) =&gt; {
      console.error(`Failed to download the task. Code: ${err}`);
    });
    <span class="hljs-comment">// downloadTask.on('progress', (receivedSize: number, totalSize: number) =&gt; {</span>
    <span class="hljs-comment">//&nbsp;&nbsp; console.log('download', "receivedSize:" + (receivedSize / 1024) + " totalSize:" + (totalSize / 1024));</span>
    <span class="hljs-comment">// });</span>
    downloadTask.on(<span class="hljs-string">'complete'</span>, async () =&gt; {
      console.log(<span class="hljs-string">'下载完成'</span>)
    })
  }
  )
    .catch((err: BusinessError) =&gt; {
      console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
    });
  <span class="hljs-keyword">this</span>.saveImageToAlbum(`${dirPath}/${fileName}`)
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-keyword">let</span> err: BusinessError = error as BusinessError;
  console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}

}

async saveImageToAlbum(path: string): Promise<boolean> { return new Promise(async (resolve: Function, reject: Function) => { try { const context = getContext(this); let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context) let srcFileUri: Array<string> = [fileUri.getUriFromPath(path)] console.debug(图片 uri is : ${<span class="hljs-built_in">JSON</span>.stringify(srcFileUri)}) let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [ { title: ‘保存图片’, fileNameExtension: ‘jpg’, // fileNameExtension: ‘mp4’, photoType: photoAccessHelper.PhotoType.IMAGE, // photoType: photoAccessHelper.PhotoType.VIDEO, // subtype: photoAccessHelper.PhotoSubtype.DEFAULT } ] let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUri, photoCreationConfigs) console.debug(目标图片 uri is : ${<span class="hljs-built_in">JSON</span>.stringify(desFileUris)}) if (desFileUris.length > 0) { //文件拷贝 for (let index = 0; index < desFileUris.length; index++) { let srcFile = fs.openSync(srcFileUri[index], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) let destFile = fs.openSync(desFileUris[index], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.copyFileSync(srcFile.fd, destFile.fd) fs.closeSync(srcFile); fs.closeSync(destFile); } resolve(true) } else { resolve(false) } } catch (err) { reject(err) } }) }

build() { RelativeContainer() { Column() { Button(‘保存图片视频到相册’) .onClick(() => { this.savePng() }) } .height(‘100%’) .width(‘100%’) .alignItems(HorizontalAlign.Center) .justifyContent(FlexAlign.Center) } } }

更多关于HarmonyOS 鸿蒙Next showAssetsCreationDialog点击允许之后相册没有生成照片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对您提到的HarmonyOS 鸿蒙Next中showAssetsCreationDialog点击允许后相册没有生成照片的问题,这通常可能与权限管理、UI线程处理或系统缓存更新有关。

  1. 权限确认:确保应用已正确获取存储权限。在鸿蒙系统中,权限管理较为严格,需用户明确授权后应用才能访问指定资源。

  2. UI线程操作:检查showAssetsCreationDialog的调用是否在UI线程进行,且后续的照片生成操作是否也遵循了UI线程的规则。非UI线程操作UI元素可能导致不可预见的行为。

  3. 系统缓存与刷新:有时系统相册的更新可能因缓存问题而延迟。尝试手动刷新相册或重启设备查看照片是否出现。

  4. 文件路径与命名:确认照片生成后的存储路径和文件名是否符合系统要求,避免使用非法字符或已被占用的文件名。

  5. 错误日志:查看应用日志,分析是否有异常抛出或错误信息,这些信息通常能提供问题的直接线索。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部