HarmonyOS鸿蒙Next中保存column中的内容到相册

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

HarmonyOS鸿蒙Next中保存column中的内容到相册

column中包含图片,用户姓名,二维码等信息,想要将这些信息当成一个图片点击保存到相册中

4 回复

参考demo

组件截图: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](/user/ohos).arkui.componentSnapshot'
import image from '[@ohos](/user/ohos).multimedia.image'
import { photoAccessHelper } from '[@kit](/user/kit).MediaLibraryKit'
import fs from '[@ohos](/user/ohos).file.fs';
import { BusinessError } from '[@ohos](/user/ohos).base';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
  [@State](/user/State) pixmap: image.PixelMap | undefined = undefined
  [@State](/user/State) saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  } // 设置安全控件按钮属性
  build() {
    Column() {
      Row() {
        Text('截图测试')
        Image($r('app.media.app_icon'))
          .autoResize(true)
          .width(200)
          .height(200)
          .margin(5)
      }
      .id("root")
      Row() {
        Image(this.pixmap).width('100%').height(200).border({ color: Color.Black, width: 2 }).margin(5)
      }
      SaveButton(this.saveButtonOptions)
        .onClick(async (event, result: SaveButtonOnClickResult) => {
          if (result == SaveButtonOnClickResult.SUCCESS) {
            try {
              // 需要确保fileUri对应的资源存在
              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)
              })
            } catch (err) {
              console.error(`create asset failed with error: ${err.code}, ${err.message}`);
            }
          } else {
            console.error('SaveButtonOnClickResult create asset failed');
          }
        })
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

更多关于HarmonyOS鸿蒙Next中保存column中的内容到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


可以使用componentSnapshot将组件截图生成图片(pixelMap形式),

再用imagePacker将图片转为ArrayBuffer形式,

配合photoAccessHelperfs获取路径、保存文件。

按钮上使用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';

@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
      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中,保存column中的内容到相册可以通过使用ImageImagePacker类来实现。首先,确保你已经获取到column中的图像数据。假设你有一个PixelMap对象,表示column中的图像内容。

使用ImagePacker类可以将PixelMap对象打包为图像文件。具体步骤如下:

  1. 创建ImagePacker实例。
  2. 使用ImagePackeraddImage方法将PixelMap对象添加到打包器中。
  3. 调用ImagePackersetFormat方法设置图像格式,如JPEG或PNG。
  4. 使用ImagePackersetQuality方法设置图像质量。
  5. 调用ImagePackerstartPacking方法开始打包,并指定输出文件路径。

完成后,图像文件将被保存到指定路径。接下来,使用MediaLibrary类将图像文件保存到相册中。具体步骤如下:

  1. 创建MediaLibrary实例。
  2. 使用MediaLibrarygetMediaAssets方法获取媒体库的根目录。
  3. 使用MediaLibrarycreateMediaAsset方法在指定目录下创建媒体资源,并指定源文件路径。

完成后,图像文件将被保存到相册中。

在HarmonyOS鸿蒙Next中,将Column中的内容保存到相册可以通过以下步骤实现:

  1. 截屏Column内容:使用PixelMapSnapshotAPI对Column进行屏幕截图,生成图像数据。
  2. 保存图像到相册:将生成的图像数据通过MediaLibraryAPI保存到设备的相册中。

具体代码示例:

// 假设column是你要截屏的组件
PixelMap pixelMap = Snapshot.takeSnapshot(column);

// 保存到相册
MediaLibrary mediaLibrary = MediaLibrary.getInstance(context);
mediaLibrary.saveImage(pixelMap, "image_name.jpg");

确保在config.json中声明了ohos.permission.WRITE_MEDIA权限。

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