HarmonyOS 网络图片地址加载完成过后保存到手机相册?

如题:HarmonyOS 网络图片地址加载完成过后保存到手机相册?

阅读 441
1 个回答

使用http模块下的request方法下载图片,并在该方法的回调函数中保存到相册。

先申请以下权限:ohos.permission.INTERNETohos.permission.WRITE\_IMAGEVIDEO 其中ohos.permission.WRITE\_IMAGEVIDEO需要向用户申请授权,可参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-ability-84-V5

保存网络图片代码如下:

import { http } from '@kit.NetworkKit'
import { BusinessError } from '@kit.BasicServicesKit';
import ResponseCode from '@ohos.net.http';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Index {
  loadImageWithUrl(url: string) {
    // 使用request下载图片并在回调函数中保存图片到相册
    http.createHttp().request(url,
      {
        method:http.RequestMethod.GET,
        connectTimeout:60000,
        readTimeout:60000
      },
      async (error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          if (ResponseCode.ResponseCode.OK === data.responseCode) {
            let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
            try {
              // 获取相册路径
              const context = getContext(this);
              let helper = photoAccessHelper.getPhotoAccessHelper(context);
              let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
              let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
              // 写入文件
              await fs.write(file.fd, imageBuffer);
              // 关闭文件
              await fs.close(file.fd);
            } catch (error) {
              console.error("error is "+ JSON.stringify(error))
            }
          } else {
            console.error("error occurred when image downloaded!")
          }
        }
      })
  }
 }
logo
HarmonyOS
子站问答
访问
宣传栏