HarmonyOS 截图保存图片到相册

通过组件截图获取到一个pixmap: image.PixelMap | undefined = undefined,怎么把这个图片保存到相册

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

可参考示例如下:

const imagePackerApi: image.ImagePacker = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30}
imagePackerApi.packing(myPixelMap, packOpts).then((ttt: ArrayBuffer)=>{
  let buf: buffer.Buffer = buffer.from(ttt);
})

import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import fs from '@ohos.file.fs';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import { common } from '@kit.AbilityKit';

const permissions: Array<Permissions> = ['ohos.permission.WRITE_IMAGEVIDEO'];

function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
  let atManager: abilityAccessCtrl.AtManager =
    abilityAccessCtrl.createAtManager();
  // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
  atManager.requestPermissionsFromUser(context, permissions).then((data) => {
    let grantStatus: Array<number> = data.authResults;
    let length: number = grantStatus.length;
    for (let i = 0; i < length; i++) {
      if (grantStatus[i] === 0) {
        // 用户授权,可以继续访问目标操作
      } else {
        // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
        return;
      }
    }
    // 授权成功 
  }).catch((err: BusinessError) => {
    console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
  })
}


@Entry
@Component
struct Index {
  @State pixmap: image.PixelMap | undefined = undefined
  aboutToAppear(): void {
    const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    reqPermissionsFromUser(permissions, context);
  }

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
        Image($r('app.media.app_icon'))
          .autoResize(true)
          .width(200)
          .height(200)
          .margin(5)
          .id("root")
      }

      Button("click to generate UI snapshot").onClick(() => {
        componentSnapshot.get("root").then((pixmap: image.PixelMap) => {
          this.pixmap = pixmap
          //保存到相册 
          let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
          const imagePackerApi = image.createImagePacker();
          imagePackerApi.packing(pixmap, packOpts).then(async (buffer: ArrayBuffer) => {
            try {
              const context = getContext(this)
              let helper = photoAccessHelper.getPhotoAccessHelper(context)
              let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
              let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
              await fs.write(file.fd, buffer);
              // 关闭文件
              await fs.close(file.fd);
            } catch (error) {
              console.error("error is " + JSON.stringify(error))
            }
          }).catch((error: BusinessError) => {
            console.error('Failed to pack the image. And the error is: ' + error);
          })
        }).catch((err: Error) => {
          console.log("error: " + err)
        })
      }).margin(10)
    }.width('100%').height('100%').alignItems(HorizontalAlign.Center)
  }
}

ohos.permission.WRITE_IMAGEVIDEO为受限开放权限:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/restricted-permissions-V5#section1417080131712

需要申请申请使用,参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/declare-permissions-in-acl-V5

分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 保存图片相册问题
400浏览 • 1回复 待解决
HarmonyOS 保存图片本地相册
21浏览 • 1回复 待解决
HarmonyOS 实现保存图片相册
17浏览 • 1回复 待解决
HarmonyOS 保存图片相册权限问题
333浏览 • 1回复 待解决
如何保存网络图片相册
765浏览 • 1回复 待解决
HarmonyOS保存图片系统相册问题咨询
684浏览 • 1回复 待解决
如何保存本地图片相册
1130浏览 • 1回复 待解决
求大佬告知如何保存图片相册
1172浏览 • 1回复 待解决
怎么实现保存网络图片相册功能?
411浏览 • 1回复 待解决
如何保存一张PNG图片相册
1881浏览 • 1回复 待解决
HarmonyOS H5页面保存图片本地相册
36浏览 • 1回复 待解决
HarmonyOS图片保存相册问题
471浏览 • 1回复 待解决
鸿蒙开发保存页面相册
6517浏览 • 1回复 待解决
HarmonyOS 图片保存相册报错
32浏览 • 1回复 待解决
HarmonyOS 相册保存图片设置title报错
402浏览 • 1回复 待解决