HarmonyOS鸿蒙Next中如何保存网络url图片和base64图片到本地相册

HarmonyOS鸿蒙Next中如何保存网络url图片和base64图片到本地相册 如何保存网络url图片和base64图片到本地相册,麻烦给个示例代码

4 回复

网络url图片:

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

async function savePhotoToGallery(context: common.UIAbilityContext) {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // onClick触发后5秒内通过createAsset接口创建图片文件,5秒后createAsset权限收回。
    let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
    // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
    let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
    context.resourceManager.getMediaContent($r('app.media.startIcon').id, 0)
      .then(async value => {
        let media = value.buffer;
        // 写到媒体库文件中
        await fileIo.write(file.fd, media);
        await fileIo.close(file.fd);
        promptAction.showToast({ message: '已保存至相册!' });
      });
  } catch (error) {
    const err: BusinessError = error as BusinessError;
    console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
  }
}

@Entry
@Component
struct Index {
  build() {
    Row() {
      Column({ space: 10 }) {
        // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
        Image($r('app.media.startIcon'))
          .height(400)
          .width('100%')

        SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
            savePhotoToGallery(context);
          } else {
            promptAction.showToast({ message: '设置权限失败!' })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
}

base64图片:先转成PixelMap

let helper = new util.Base64Helper();
let buffer: ArrayBuffer = helper.decodeSync(this.base64, util.Type.MIME).buffer as ArrayBuffer;
let imageSource = image.createImageSource(buffer);
let opts: image.DecodingOptions = { editable: true };
this.pixel = await imageSource.createPixelMap(opts);

再将pixelMap保存到相册:

async function savePixelMapToAlbum() {
  // 获取相册的保存路径
  let helper = photoAccessHelper.getPhotoAccessHelper(this.context);
  let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpeg');
  let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  let imagePackerApi = image.createImagePacker();
  let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };

  imagePackerApi.packToFile(this.pixel, file.fd, packOpts, (err: BusinessError) => {
    if (err) {
      console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
    } else {
      console.info('Succeeded in packing the image to file.');
      promptAction.showToast({ message: '已保存至相册!' });
    }
  })
}

更多关于HarmonyOS鸿蒙Next中如何保存网络url图片和base64图片到本地相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,保存网络URL图片和Base64图片到本地相册可以通过ImageFileIO模块实现。对于网络URL图片,使用Image模块的createImageSource方法从网络获取图片资源,然后通过createPixelMap方法生成像素图,最后使用FileIO模块的write方法将像素图保存到本地相册。对于Base64图片,先将Base64字符串解码为字节数组,然后使用FileIO模块的write方法将字节数组保存为图片文件并存储到相册。具体实现如下:

  1. 网络URL图片保存:
import image from '@ohos.multimedia.image';
import fileio from '@ohos.fileio';

async function saveUrlImageToAlbum(url, fileName) {
    const imageSource = image.createImageSource(url);
    const pixelMap = await imageSource.createPixelMap();
    const filePath = /storage/emulated/0/Pictures/${fileName}.jpg;
    const file = await fileio.open(filePath, fileio.OpenMode.CREATE | fileio.OpenMode.READ_WRITE);
    await pixelMap.encodeToFile(filePath, image.ImageFormat.JPEG, 100);
    fileio.close(file);
}
  1. Base64图片保存:
import fileio from '@ohos.fileio';
import util from '@ohos.util';

function saveBase64ImageToAlbum(base64Str, fileName) {
    const base64Helper = new util.Base64Helper();
    const byteArray = base64Helper.decode(base64Str);
    const filePath = /storage/emulated/0/Pictures/${fileName}.jpg;
    const file = fileio.openSync(filePath, fileio.OpenMode.CREATE | fileio.OpenMode.READ_WRITE);
    fileio.writeSync(file.fd, byteArray);
    fileio.closeSync(file);
}

在HarmonyOS鸿蒙Next中,保存网络URL图片和Base64图片到本地相册可以通过以下步骤实现:

  1. 网络URL图片:

    • 使用ohos.net.http模块下载图片数据。
    • 将下载的图片数据保存到本地文件系统。
    • 使用@ohos.multimedia.mediaLibrary模块将文件插入到相册中。
  2. Base64图片:

    • 将Base64字符串解码为二进制数据。
    • 将二进制数据保存到本地文件系统。
    • 使用@ohos.multimedia.mediaLibrary模块将文件插入到相册中。

具体代码实现可参考鸿蒙官方文档,确保权限申请和错误处理完善。

回到顶部