HarmonyOS 鸿蒙Next 如何将一个https的图片保存到相册呢

HarmonyOS 鸿蒙Next 如何将一个https的图片保存到相册呢 如何将一个https的图片保存到相册呢

11 回复

可以先下载到本地,然后写入相册

更多关于HarmonyOS 鸿蒙Next 如何将一个https的图片保存到相册呢的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


有具体的api和例子吗

有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html

先存入app沙盒内,再存入 相册中,

下载https文件错误码8怎么解决呢?

有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html

我想问一下,图片已经下载到app沙箱中,然后怎么才能在相册中读取到呢,

在HarmonyOS鸿蒙Next中,可以通过以下步骤将一个HTTPS图片保存到相册:

  1. 使用Http模块发起网络请求,获取图片的二进制数据。
  2. 将获取到的二进制数据转换为PixelMap对象。
  3. 使用ImagePackerPixelMap对象编码为图片文件。
  4. 使用MediaLibrary模块将图片文件保存到相册。

具体代码如下:

import http from '@ohos.net.http';
import image from '@ohos.multimedia.image';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

async function saveImageToGallery(url: string) {
    // 发起网络请求获取图片数据
    let httpRequest = http.createHttp();
    let response = await httpRequest.request(url, {
        method: http.RequestMethod.GET,
        expectDataType: http.HttpDataType.ARRAY_BUFFER
    });
    let arrayBuffer = response.result as ArrayBuffer;

    // 将ArrayBuffer转换为PixelMap
    let imageSource = image.createImageSource(arrayBuffer);
    let pixelMap = await imageSource.createPixelMap();

    // 将PixelMap编码为图片文件
    let imagePacker = image.createImagePacker();
    let packOpts = { format: 'image/jpeg', quality: 100 };
    let imageData = await imagePacker.packing(pixelMap, packOpts);

    // 保存图片到相册
    let media = mediaLibrary.getMediaLibrary();
    let fileAsset = await media.createAsset(mediaLibrary.MediaType.IMAGE, 'image.jpg');
    await fileAsset.write(imageData);
}

该代码通过Http模块获取图片数据,使用Image模块处理图片,最后通过MediaLibrary模块将图片保存到相册。

回到顶部