HarmonyOS 现有一个网络地址的图片, 怎么保存到相册

HarmonyOS
2024-12-24 18:05:15
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
shlp

可以考虑通过安全控件savebutton创建媒体资源,不需要WRITE_IMAGEVIDEO权限。

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-savebutton-V5

示例参考如下:

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

@Entry
@Component
struct Index {
  @State imageBuffer: ArrayBuffer | undefined = undefined; // 图片ArrayBuffer
  @State image: PixelMap | undefined = undefined;
  @State photoAccessHelper: photoAccessHelper.PhotoAccessHelper | undefined = undefined; // 相册模块管理实例

  async aboutToAppear(): Promise<void> {
    this.getPicture();
  }

  build() {
    Row() {
      Column() {
        Image(this.image)
          .objectFit(ImageFit.Contain)
          .width('50%')

        SaveButton()
          .onClick(async () => {
            if (this.imageBuffer !== undefined) {
              await this.saveImage(this.imageBuffer);
              promptAction.showToast({
                message: "成功",
                duration: 2000
              })
            }
          })

      }.width('100%')
    }.height('100%')
  }

  /**
   * 通过http的request方法从网络下载图片资源
   */
  async getPicture() {
    http.createHttp()// 显示网络图片的地址
      .request('https://myImg.jpg',
        (error: BusinessError, data: http.HttpResponse) => {
          if (error) {
            // 下载失败时弹窗提示检查网络,不执行后续逻辑
            promptAction.showToast({
              message: "请求失败",
              duration: 2000
            })
            console.error('-----' + error.message)
            return;
          }
          this.transcodePixelMap(data);
          // 判断网络获取到的资源是否为ArrayBuffer类型
          if (data.result instanceof ArrayBuffer) {
            this.imageBuffer = data.result as ArrayBuffer;
          }
        }
      )
  }

  /**
   * 使用createPixelMap将ArrayBuffer类型的图片装换为PixelMap类型
   * @param data:网络获取到的资源
   */
  transcodePixelMap(data: http.HttpResponse) {
    if (ResponseCode.ResponseCode.OK === data.responseCode) {
      const imageData: ArrayBuffer = data.result as ArrayBuffer;
      // 通过ArrayBuffer创建图片源实例。
      const imageSource: image.ImageSource = image.createImageSource(imageData);
      const options: image.InitializationOptions = {
        'alphaType': 0, // 透明度
        'editable': false, // 是否可编辑
        'pixelFormat': 3, // 像素格式
        'scaleMode': 1, // 缩略值
        'size': { height: 100, width: 100 }
      }; // 创建图片大小

      // 通过属性创建PixelMap
      imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
        this.image = pixelMap;
      });
    }
  }

  /**
   * 保存ArrayBuffer到图库
   * @param buffer:图片ArrayBuffer
   * @returns
   */
  async saveImage(buffer: ArrayBuffer | string): Promise<void> {
    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, buffer);
    await fs.close(file.fd);
  }

  /**
   * 保存ArrayBuffer到用户选择的路径
   * @param buffer:图片ArrayBuffer
   * @returns
   */
  // async pickerSave(buffer: ArrayBuffer | string): Promise<void> {
  //   const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例
  //   photoSaveOptions.newFileNames = ['PhotoViewPicker ' + new Date().getTime() + '.jpg']; // 保存文件名(可选)
  //   const photoViewPicker = new picker.PhotoViewPicker;
  //   photoViewPicker.save(photoSaveOptions)
  //     .then(async (photoSvaeResult) => {
  //       const uri = photoSvaeResult[0];
  //       const file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  //       await fs.write(file.fd, buffer);
  //       await fs.close(file.fd);
  //       promptAction.showToast({
  //         message: "save picture",
  //         duration: 2000
  //       })
  //     });
  // }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
分享
微博
QQ
微信
回复
2024-12-24 19:45:37
相关问题
获取网络图片保存到相册
2851浏览 • 1回复 待解决
HarmonyOS 图片保存到相册
838浏览 • 1回复 待解决
HarmonyOS 图片保存到相册报错
1044浏览 • 1回复 待解决
HarmonyOS Image图片部分网络地址不显示
794浏览 • 1回复 待解决
HarmonyOS 网络地址格式校验--
712浏览 • 1回复 待解决
网络地址建立socket连接
1538浏览 • 1回复 待解决
使用http请求网络地址
1717浏览 • 1回复 待解决
HarmonyOS 如何将图片保存到相册
790浏览 • 1回复 待解决
怎么实现保存网络图片相册功能?
1612浏览 • 1回复 待解决
HarmonyOS如何把图片保存到手机相册
1580浏览 • 1回复 待解决
HarmonyOS 如何把base64图片保存到相册
1387浏览 • 1回复 待解决
如何把图片和文案结合,保存到相册
1310浏览 • 0回复 待解决
如何保存网络图片相册
1675浏览 • 1回复 待解决
怎么把视频保存到相册以及主机端?
4957浏览 • 1回复 待解决