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

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

示例代码如下:

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: '保存失败' })
    })
  }
}

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

4 回复

不行,二选一

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


示例代码看了吗,上面的代码就是实现方案啊,

是的 先存到沙箱路径再用showAssetsCreationDialog,

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

  1. 获取PixelMap对象:确保你已经有一个PixelMap对象。
  2. 转换为ImageSource:使用ImageSource.createFromPixelMap(pixelMap)将PixelMap转换为ImageSource。
  3. 保存到相册:使用ImagePacker将ImageSource打包为图片文件,并保存到相册目录。

示例代码:

ImageSource imageSource = ImageSource.createFromPixelMap(pixelMap);
ImagePacker imagePacker = ImagePacker.create();
ImagePacker.PackingOptions options = new ImagePacker.PackingOptions();
options.format = "image/jpeg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "image.jpg");
imagePacker.pack(imageSource, new FileOutputStream(file), options);
回到顶部