如何保存pixelmap图片到相册,不使用SaveButton,不申请受控权限 - HarmonyOS 鸿蒙Next

如何保存pixelmap图片到相册,不使用SaveButton,不申请受控权限 - HarmonyOS 鸿蒙Next

示例代码如下:

import componentSnapshot from '@ohos.arkui.componentSnapshot'
import { image } from '@kit.ImageKit'
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import fs from '@ohos.file.fs';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo, fileUri } from '@kit.CoreFileKit';

@Component
export struct SavePixelMap {
  build() {
    Column() {
      Column() {
        Text('文字123')
        Text('文字456')
        SymbolGlyph($r('sys.symbol.save'))
      }
      .justifyContent(FlexAlign.Center)
      .backgroundColor(0xdddddd)
      .height('20%')
      .width('100%')
      .id('snapshot') // 绑定id

      Button('保存图片')
        .onClick(() => {
          try {
            componentSnapshot.get('snapshot'/*截图组件绑定的id*/, async (error: Error, pixelMap: image.PixelMap) => {
              if (pixelMap) {
                this.saveImage(pixelMap)
              } else {
                promptAction.showToast({ message: '保存失败' })
              }
            }, { scale: 0.5 })
          } catch (error) {
            promptAction.showToast({ message: '保存失败' })
          }
        })
    }
    .height('100%')
    .width('100%')
  }

  //保存图片
  async saveImage(pixelMap: PixelMap) {
    let imagePackerApi = image.createImagePacker();
    const packOptions: image.PackingOption = {
      format: 'image/png',
      quality: 100
    }
    imagePackerApi.packing(pixelMap, packOptions).then((buffer: ArrayBuffer) => {
      try {
        const context = getContext()

        // 应用沙箱路径
        let path = context.filesDir + '/test.png'
        // 在沙箱新建并打开文件
        let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        // 写入pixelMap图片内容
        fs.writeSync(file.fd, buffer);
        // 关闭文件
        fs.closeSync(file.fd);
        
        // 使用showAssetsCreationDialog保存沙箱中的图片
        let srcFileUris: Array<string> = [fileUri.getUriFromPath(context.filesDir + '/test.png')];
        let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
          {
            title: 'test', // 可选
            fileNameExtension: 'png',
            photoType: photoAccessHelper.PhotoType.IMAGE,
            subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
          },
        ];
        photoAccessHelper.getPhotoAccessHelper(context)
          .showAssetsCreationDialog(srcFileUris, photoCreationConfigs)
          .then((desFileUris: Array<string>) => {
            let imageFile1 = fileIo.openSync(desFileUris[0], fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
            fileIo.copyFileSync(context.filesDir + '/test.png', imageFile1.fd, 0)
            fileIo.closeSync(imageFile1.fd)
            promptAction.showToast({ message: '保存成功' })
          });
      } catch (error) {
        promptAction.showToast({ message: '保存失败' })
      }

    }).catch((error: BusinessError) => {
      promptAction.showToast({ message: '保存失败' })
    })
  }
}

更多关于如何保存pixelmap图片到相册,不使用SaveButton,不申请受控权限 - HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于如何保存pixelmap图片到相册,不使用SaveButton,不申请受控权限 - HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,保存PixelMap图片到相册且不使用SaveButton以及不申请受控权限,可以通过以下步骤实现:

  1. 获取PixelMap对象:确保你已经有一个PixelMap对象,通常是通过图像处理或解码获得的。

  2. 创建ImagePacker对象:使用ImagePacker类将PixelMap对象编码为图片文件格式(如JPEG或PNG)。

  3. 保存到相册:将编码后的图片数据写入文件,并保存到设备的相册目录中。

具体代码示例如下:

import image from '@ohos.multimedia.image';
import fileio from '@ohos.fileio';
import file from '@ohos.file';

async function savePixelMapToGallery(pixelMap: image.PixelMap) {
    // 创建ImagePacker对象
    const imagePacker = image.createImagePacker();

    // 设置打包选项
    const packOptions = {
        format: "image/jpeg", // 或 "image/png"
        quality: 100 // 图片质量
    };

    // 将PixelMap打包为ArrayBuffer
    const arrayBuffer = await imagePacker.packing(pixelMap, packOptions);

    // 定义文件路径
    const galleryPath = file.DirCache + "/image.jpg";

    // 将ArrayBuffer写入文件
    const fd = fileio.openSync(galleryPath, fileio.OpenMode.CREAT | fileio.OpenMode.RDWR);
    fileio.writeSync(fd, arrayBuffer);
    fileio.closeSync(fd);

    // 将文件移动到相册目录
    const destPath = file.DirPictures + "/image.jpg";
    file.move(galleryPath, destPath).then(() => {
        console.log("图片已保存到相册");
    }).catch((err) => {
        console.error("保存图片失败:", err);
    });
}

这段代码将PixelMap对象编码为JPEG格式,并将其保存到设备的相册目录中,整个过程不需要使用SaveButton和申请受控权限。

回到顶部