HarmonyOS 鸿蒙Next 保存base64图片到相册

发布于 1周前 作者 itying888 最后一次编辑是 5天前 来自 鸿蒙OS

下面这段代码有什么问题吗?

import { common } from '@kit.AbilityKit';
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { buffer } from '@kit.ArkTS';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import image from '@ohos.multimedia.image';

@Entry
@Component
struct SaveAlbum {
  @State Base64: string = ''

  async pixelToBase64(pixelMap: PixelMap) {
    // 转换成base64
    const imagePackerApi: image.ImagePacker = image.createImagePacker();
    let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
    const data = await imagePackerApi.packing(pixelMap, packOpts);
    let buf: buffer.Buffer = buffer.from(data);
    return 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);

  }

  writeFile(data: string): string {
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    let uri = ''
    try {
      let filePath = filesDir + "/1.jpg";
      uri = fileUri.getUriFromPath(filePath);
      let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      console.info("file fd: " + file.fd);
      const reg = new RegExp("data:image/\\w+;base64,")
      const base64 = data.replace(reg, "");
      console.log("base64flag", base64)
      const dataBuffer = buffer.from(base64, 'base64')
      let writeLen = fileIo.writeSync(file.fd, dataBuffer.buffer);
      fileIo.closeSync(file);
    } catch (Error) {
    }
    return uri
  }

  async SavePicture() {
    try {
      let context = getContext(this) as common.UIAbilityContext;
      let windowClass: window.Window | undefined = undefined;
      window.getLastWindow(context, async (err: BusinessError, data) => {
        windowClass = data;
        let pixelMap = await windowClass.snapshot();
        this.Base64 = await this.pixelToBase64(pixelMap);
        let uri = this.writeFile(this.Base64)
        let srcFileUris: Array<string> = [
          uri
        ];
        let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
          {
            title: '',
            fileNameExtension: 'jpg',
            photoType: photoAccessHelper.PhotoType.IMAGE,
            subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
          }
        ];
        let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
        let desFileUris: Array<string> =
          await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
        console.info('showAssetsCreationDialog success, data is ' + desFileUris);
      })


    } catch (err) {
      console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
    }
  }

  build() {
    RelativeContainer() {
      Button('保存图片')
        .onClick(() => {
          this.SavePicture()
        })
    }
    .height('100%')
    .width('100%')
  }
}

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

2 回复
import { common } from '@kit.AbilityKit';
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { buffer } from '@kit.ArkTS';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { promptAction, window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct photo_240912161900073 {
  @State Base64: string = ''

  async pixelToBase64(pixelMap: PixelMap) {
    // 转换成base64
    const imagePackerApi: image.ImagePacker = image.createImagePacker();
    let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
    const data = await imagePackerApi.packing(pixelMap, packOpts);
    let buf: buffer.Buffer = buffer.from(data);
    return 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);

  }

  writeFile(data: string): string {
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    let uri = ''
    try {
      let filePath = filesDir + "/1.jpg";
      uri = fileUri.getUriFromPath(filePath);
      let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      console.info("file fd: " + file.fd);
      const reg = new RegExp("data:image/\\w+;base64,")
      const base64 = data.replace(reg, "");
      console.log("base64flag", base64)
      const dataBuffer = buffer.from(base64, 'base64')
      let writeLen = fileIo.writeSync(file.fd, dataBuffer.buffer);
      fileIo.closeSync(file);
    }
    catch (Error) {}
    return uri
  }

  async SavePicture() {
    try {
      let context = getContext(this) as common.UIAbilityContext;
      let windowClass: window.Window | undefined = undefined;
      window.getLastWindow(context, async (err: BusinessError, data) => {
        windowClass = data;
        let pixelMap = await windowClass.snapshot();
        this.Base64 = await this.pixelToBase64(pixelMap);
        this.Base64 = '*******';

        let uri = this.writeFile(this.Base64)
        console.log("保存的路径"+uri)
        let srcFileUris: Array<string> = [
        // 获取需要保存到媒体库的位于应用沙箱的图片/视频uri
          uri
        ];
        let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
          {
            title: '1',
            fileNameExtension: 'jpg',
            photoType: photoAccessHelper.PhotoType.IMAGE,
            subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
          }
        ];
        let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
        let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
        console.info('showAssetsCreationDialog success, data is ' + desFileUris);

        try {
          // 通过uri打开媒体库文件
          if (desFileUris.length>0) {
            console.log("desFileUris[0]:"+desFileUris.length)

            //获取图片的base64字符串
            let imageStr = '******'.split(',');
            //打开文件
            let file = fs.openSync(desFileUris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            //base64字符串转成
            const decodeBuffer = buffer.from(imageStr.toString(), 'base64').buffer;
            //写入文件
            fs.writeSync(file.fd, decodeBuffer);
            fs.closeSync(file.fd);
            promptAction.showToast({ message: '已保存至相册!' })
          }else {
            promptAction.showToast({ message: '拒绝!' })
          }

        } catch (err) {
          console.info(err)
          promptAction.showToast({ message: '保存失败!' })
        }


      })
    } catch (err) {
      console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
    }
  }

  build() {
    RelativeContainer() {
      Column(){
        Button('保存图片')
          .margin(10)
          .onClick(() => {
            this.SavePicture()
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}

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


在HarmonyOS鸿蒙Next系统中保存base64编码的图片到相册,可以通过以下步骤实现:

  1. 解码Base64字符串:首先,将base64编码的字符串解码为二进制数据。这通常可以使用Java或Kotlin中的Base64解码类来完成,例如Base64.decode方法。

  2. 转换为Bitmap对象:解码后的二进制数据需要被转换为Bitmap对象,以便在Android或鸿蒙系统中进行图像处理。这可以通过BitmapFactory.decodeByteArray方法实现。

  3. 保存到相册:在鸿蒙系统中,保存Bitmap到相册通常涉及到使用MediaStore API或系统提供的文件存储API。你需要创建一个ContentValues对象,并设置必要的元数据(如MIME类型、标题等),然后使用ContentResolver.insert方法将Bitmap保存到系统的MediaStore中。

  4. 处理权限:确保你的应用具有写入外部存储的权限。在鸿蒙系统中,这通常需要在manifest文件中声明权限,并在运行时请求用户授权。

以上步骤涵盖了从base64字符串解码到保存到相册的整个过程。如果在实现过程中遇到具体问题,可能需要检查你的代码逻辑、权限配置或系统API的使用方式。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部