【示例代码分享】HarmonyOS鸿蒙Next中容器组件截图并保存到相册

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

【示例代码分享】HarmonyOS鸿蒙Next中容器组件截图并保存到相册 使用componentSnapshot将组件截图生成图片(pixelMap形式),
再用imagePacker将图片转为ArrayBuffer形式,
配合photoAccessHelper、fs获取路径、保存文件。
按钮上使用SaveButton进行保存图片(无需额外申请权限)

参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-arkui-componentsnapshot-V5
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-savebutton-V5

话不多说,直接上代码及效果图:

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';

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

      // 保存按钮 (鸿蒙安全控件的保存控件)文档:[https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-security-components-savebutton-V5#savebutton-1](https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-security-components-savebutton-V5#savebutton-1)
      SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE_IMAGE, buttonType: ButtonType.Normal })
        .layoutDirection(SecurityComponentLayoutDirection.VERTICAL)
        .backgroundColor(Color.White)
        .iconSize(28)
        .iconColor(0x818181)
        .fontSize(12)
        .fontColor(0x818181)
        .borderRadius(12)
        .width(70)
        .height(70)
        .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result == SaveButtonOnClickResult.SUCCESS) {
            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/jpeg',
      quality: 100
    }
    imagePackerApi.packing(pixelMap, packOptions).then(async (buffer : ArrayBuffer) => {
      try {
        const context = getContext()
        let helper = photoAccessHelper.getPhotoAccessHelper(context)
        // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
        let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
        let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        await fs.write(file.fd, buffer);
        // 关闭文件
        await fs.close(file.fd);
        promptAction.showToast({message:'保存成功'})
      }
      catch (error) {
        promptAction.showToast({message:'保存失败'})
      }

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

更多关于【示例代码分享】HarmonyOS鸿蒙Next中容器组件截图并保存到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中,可以使用ComponenttakeSnapshot方法对容器组件进行截图,并通过MediaLibrary将截图保存到相册。以下是一个示例代码:

import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import { Component } from '@ohos.arkui.component';

async function saveSnapshotToAlbum(component: Component) {
  try {
    // 截图
    const snapshot = await component.takeSnapshot();
    
    // 获取媒体库实例
    const media = mediaLibrary.getMediaLibrary();
    
    // 创建文件
    const file = await media.createAsset(mediaLibrary.MediaType.IMAGE, 'snapshot.png');
    
    // 写入文件
    await file.write(snapshot);
    
    console.log('截图已保存到相册');
  } catch (error) {
    console.error('保存截图失败:', error);
  }
}

该代码首先使用takeSnapshot方法对指定的容器组件进行截图,然后通过MediaLibrary将截图保存到相册中。

更多关于【示例代码分享】HarmonyOS鸿蒙Next中容器组件截图并保存到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过PixelMapImageSaver实现容器组件的截图并保存到相册。以下是一个示例代码:

import image from '@ohos.multimedia.image';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

async function captureAndSave(component: any) {
  // 创建PixelMap对象
  const pixelMap = await image.createPixelMapFromSurface(component.getSurface());

  // 获取媒体库实例
  const media = mediaLibrary.getMediaLibrary();

  // 创建图片保存选项
  const options = {
    name: 'screenshot.png',
    relativePath: 'Pictures/'
  };

  // 保存图片到相册
  await media.createAsset(mediaLibrary.MediaType.IMAGE, 'screenshot.png', options, pixelMap);
}

此代码将指定组件的截图保存到相册中。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!