HarmonyOS 某个组件截图成功后, 如何将image.PixelMap类型的结果保存至系统相册或者本地app沙箱

生成某个视图快照后, 如何将图片保存至系统相册与本地沙箱

componentSnapshot.get('组件id', async(error: Error, pixmap: image.PixelMap) => {
  if (!error && pixmap) {
    // 怎么将  pixmap类型 写入系统相册与沙箱, 是否可以不用请求相册权限?
  }
}
HarmonyOS
2024-12-27 16:42:44
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

可参考:

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);
  let base64urlStr: string =  buf.toString('base64url');
  console.info("base64urlStr:" + base64urlStr)
  this.imageBuffer = buf.buffer
  this.base64urlStr = buf.toString('base64url')
  console.info("imageBuffer1:" + this.imageBuffer.byteLength)
})


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)
  }
}
分享
微博
QQ
微信
回复
2024-12-27 19:24:08
相关问题
HarmonyOS如何将PixelMap保存相册
721浏览 • 1回复 待解决
HarmonyOS 如何将PixelMap保存沙箱
145浏览 • 1回复 待解决
HarmonyOS image.PixelMap拉伸变形
175浏览 • 1回复 待解决
HarmonyOS 如何将图片保存相册
115浏览 • 1回复 待解决
如何将Pixmap保存本地文件?
598浏览 • 1回复 待解决
HarmonyOS 截图保存图片到相册
185浏览 • 1回复 待解决
HarmonyOS 如何将base64图片保存相册
1229浏览 • 1回复 待解决
如何将视频保存相册以及主机端
5816浏览 • 1回复 待解决
如何将app.media.app_icon,转换为PixelMap
2233浏览 • 1回复 待解决
有谁知道如何将图片保存相册
1296浏览 • 1回复 待解决