HarmonyOS 保存网络图片到手机图库?

如题:HarmonyOS 保存网络图片到手机图库?

阅读 496
1 个回答

参考以下demo:

import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import promptAction from '@ohos.promptAction';

@Entry
@Component
export struct SaveNetWorkPictures {
  imageBuffer: ArrayBuffer | undefined = undefined; // 图片ArrayBuffer

  async aboutToAppear(): Promise<void> {
    //请求网络图片
    //this.getPicture();
  }

  build() {
    Column() {
      Column() {
        SaveButton({ icon: SaveIconStyle.FULL_FILLED })
          .iconSize(60)
          .iconColor("#888888")
          .width(99)
          .height(99)
          .onClick(async () => {
            // if (this.imageBuffer !== undefined) {
            // await this.getPicture();
            await this.saveImage(this.imageBuffer);
            promptAction.showToast({
              message: '图片保存成功',
              duration: 2000
            })
            // }
          })
      }
      .height('100%')
      .padding(100)
    }
  }

  // * 通过http的request方法从网络下载图片资源
  getPicture(): Promise<void> {
    return new Promise((resolve)=>{
      http.createHttp()// 显示网络图片的地址
        .request('https:xxx',
          (error: BusinessError, data: http.HttpResponse) => {
            if (error) {
              // 下载失败时弹窗提示检查网络,不执行后续逻辑
              promptAction.showToast({
                message: '图片加载失败,请检查网络',
                duration: 2000
              })
              return;
            }

            // this.transcodePixelMap(data);
            // 判断网络获取到的资源是否为ArrayBuffer类型
            if (data.result instanceof ArrayBuffer) {
              this.imageBuffer = data.result as ArrayBuffer;
            }
            resolve();
          }
        )
    })

  }

  // * 保存ArrayBuffer到图库
  async saveImage(buffer: ArrayBuffer | string | undefined): Promise<void> {
    if(this.imageBuffer == undefined ){
      await this.getPicture()
    }
    try {
      const context = getContext(this) as common.UIAbilityContext; // 获取getPhotoAccessHelper需要的context
      const helper = photoAccessHelper.getPhotoAccessHelper(context); // 获取相册管理模块的实例
      const uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 指定待创建的文件类型、后缀和创建选项,创建图片或视频资源
      const file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      await fs.write(file.fd, this.imageBuffer);
      await fs.close(file.fd);
    } catch (e) {
      console.log(JSON.stringify(e))
    }
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏