HarmonyOS鸿蒙Next中如何将PixelMap保存到本地相册中

HarmonyOS鸿蒙Next中如何将PixelMap保存到本地相册中 第一步: 使用componentSnapshot截图

componentSnapshot.get('root', (err: BusinessError, pixelMap: image.PixelMap) => {
  if (err) {
    //截图失败
    savePicToGalleryPlugin.onFailCall()
  } else {
    //截图成功
    savePicToGalleryPlugin.onSuccessCall(pixelMap,params)
  }
}),

第二步: 截图成功后在onSuccessCall里面对pixelMap处理保存到本地相册


更多关于HarmonyOS鸿蒙Next中如何将PixelMap保存到本地相册中的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

可以参考以下demo:

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 = this.getContext() 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 = this.getContext()
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)
}

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


在HarmonyOS鸿蒙Next中,将PixelMap保存到本地相册可以通过PhotoAccessHelperImagePacker类实现。首先,使用ImagePacker将PixelMap转换为JPEG或PNG格式的字节数组。然后,通过PhotoAccessHelper将字节数组写入到本地相册中。具体步骤如下:

  1. 创建ImagePacker对象:使用ImagePacker.create()方法创建ImagePacker对象。
  2. 设置ImagePacker参数:通过ImagePackersetFormat方法设置输出格式为JPEG或PNG。
  3. 将PixelMap转换为字节数组:调用ImagePackeraddImage方法将PixelMap添加到打包器中,然后使用getPackedBytes方法获取字节数组。
  4. 获取PhotoAccessHelper实例:通过PhotoAccessHelper.getPhotoAccessHelper(context)获取PhotoAccessHelper实例。
  5. 创建相册文件:使用PhotoAccessHelpercreateAsset方法在相册中创建一个新的文件。
  6. 写入字节数组:通过PhotoAccessHelperwriteFile方法将字节数组写入到创建的文件中。

示例代码:

import image from '@ohos.multimedia.image';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

async function savePixelMapToAlbum(pixelMap: image.PixelMap, context: Context) {
    const imagePacker = image.createImagePacker();
    imagePacker.setFormat("image/jpeg");
    imagePacker.addImage(pixelMap);
    const packedBytes = await imagePacker.getPackedBytes();

    const photoAccessHelperInstance = photoAccessHelper.getPhotoAccessHelper(context);
    const photoAsset = await photoAccessHelperInstance.createAsset("IMG_", "JPEG");
    await photoAccessHelperInstance.writeFile(photoAsset.uri, packedBytes);
}

以上代码展示了如何将PixelMap保存到本地相册中。

在HarmonyOS鸿蒙Next中,将PixelMap保存到本地相册的步骤如下:

  1. 创建ImageSaver实例:使用ImageSaver类来保存图像。
  2. 设置保存路径:指定保存图像的路径,通常为相册目录。
  3. 保存PixelMap:调用ImageSaver.save方法将PixelMap保存到指定路径。

示例代码:

ImageSaver imageSaver = new ImageSaver(context);
imageSaver.setPath("/sdcard/Pictures/"); // 设置保存路径
imageSaver.save(pixelMap); // 保存PixelMap

确保应用具有写外部存储的权限,并在AndroidManifest.xml中声明:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

通过以上步骤,即可将PixelMap保存到本地相册中。

回到顶部