HarmonyOS 鸿蒙Next 保存PixelMap到相册
HarmonyOS 鸿蒙Next 保存PixelMap到相册
可以参考demo
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction';
import { image } from '@kit.ImageKit';
@Entry
@Component
struct Index {
@State icon: image.PixelMap | undefined = undefined;
build() {
Row() {
Column({ space: 10 }) {
SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
const context: common.UIAbilityContext =
getContext(this) as common.UIAbilityContext; // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
this.savePhotoToGallery(context);
} else {
promptAction.showToast({ message: '设置权限失败!' })
}
})
}.width('100%')
}.height('100%').backgroundColor(0xF1F3F5)
}
async savePhotoToGallery(context: common.UIAbilityContext) {
const imagePackerApi: image.ImagePacker = image.createImagePacker();
const color: ArrayBuffer =
new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4
let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
this.icon = await image.createPixelMap(color, opts);
image.createPixelMap(color, opts).then((pixelMap: image.PixelMap) => {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }
imagePackerApi.packing(pixelMap, packOpts).then(async (buffer: ArrayBuffer) => {
console.info('Succeeded in packing the image.');
let helper = photoAccessHelper.getPhotoAccessHelper(context)
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE,
'png') // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
try {
context.resourceManager.getMediaContent($r('app.media.startIcon').id, 0)
.then(async value => {
let media = value.buffer;
// 写到媒体库文件中
await fs.write(file.fd, media);
await fs.close(file.fd);
promptAction.showToast({ message: '已保存至相册!' });
});
}
catch (err) {
console.error("error is "+ JSON.stringify(err))
}
})
})
}
}
更多关于HarmonyOS 鸿蒙Next 保存PixelMap到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙)系统中保存PixelMap到相册,通常需要以下几个步骤:
-
权限申请:首先,确保你的应用已申请并获得了存储权限(WRITE_EXTERNAL_STORAGE)和读写媒体文件权限(READ_MEDIA_FILES和WRITE_MEDIA_FILES)。这些权限在manifest文件中声明,并在运行时请求。
-
创建Bitmap:由于PixelMap不是直接用于保存为图像文件的格式,你需要将其转换为Bitmap。使用
PixelMap.toBitmap()
方法可以实现这一转换。 -
保存Bitmap到相册:使用MediaStore API来保存Bitmap。创建一个ContentValues对象,设置图像的相关信息(如MIME类型、标题、日期等),然后使用
getContentResolver().insert()
方法将Bitmap插入到MediaStore中,这样图像就会被保存到相册。 -
处理异常:在整个过程中,要妥善处理可能发生的IOException和SecurityException等异常。
-
更新媒体库:保存后,可能需要通知系统媒体库更新,以确保新保存的图像立即显示在相册中。
如果上述步骤正确执行,你应该能够成功将PixelMap保存到相册。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html