HarmonyOS 鸿蒙Next 将image.PixelMap类型的图片保存到本地,保存成功但是需要杀应用后台系统相册才会显示照片
HarmonyOS 鸿蒙Next 将image.PixelMap类型的图片保存到本地,保存成功但是需要杀应用后台系统相册才会显示照片
将image.PixelMap类型的图片保存到本地,保存成功但是需要杀应用后台系统相册才会显示照片
参考代码:
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-image-20-V5
更多关于HarmonyOS 鸿蒙Next 将image.PixelMap类型的图片保存到本地,保存成功但是需要杀应用后台系统相册才会显示照片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
需要杀掉进程才可以保存成功,应该是文件资源没有释放,所以没有保存结束,当杀掉进程,自动回收资源,保存成功。
import { resourceManager } from '@kit.LocalizationKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { promptAction } from '@kit.ArkUI';
import { fileIo } from '@kit.CoreFileKit';
@Entry
@Component
struct SavePixelMapToAlbum {
@State saveButtonOptions: SaveButtonOptions = {
icon: SaveIconStyle.FULL_FILLED,
text: SaveDescription.SAVE,
buttonType: ButtonType.Capsule
};
@State pixel: image.PixelMap | undefined = undefined;
@State albumPath: string = '';
@State photoSize: number = 0;
private context: Context = getContext(this);
async aboutToAppear() {
const resourceMgr: resourceManager.ResourceManager = this.context.resourceManager;
const fileData: Uint8Array = await resourceMgr.getRawFileContent('rawfile/test.png');
let buffer = new Uint8Array(fileData).buffer as object as ArrayBuffer;
let imageResource = image.createImageSource(buffer);
let opts: image.DecodingOptions = { editable: true };
this.pixel = await imageResource.createPixelMap(opts);
}
async savePixelMapToAlbum() {
let imagePackerApi = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };
imagePackerApi.packing(this.pixel, packOpts).then(async (buffer: ArrayBuffer) => {
try {
let helper = photoAccessHelper.getPhotoAccessHelper(this.context)
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
await fileIo.write(file.fd, buffer);
// 关闭文件
await fileIo.close(file.fd);
promptAction.showToast({ message: '已保存至相册!' });
} catch (error) {
console.error("保存失败:" + JSON.stringify(error))
}
}).catch((error: BusinessError) => {
console.error('保存失败,失败原因: ' + error);
})
}
build() {
Row() {
Column() {
Image(this.pixel)
.objectFit(ImageFit.None)
.height('30%')
SaveButton(this.saveButtonOptions)
.onClick(async (event, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
this.savePixelMapToAlbum();
}
})
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS 鸿蒙Next 将image.PixelMap类型的图片保存到本地,保存成功但是需要杀应用后台系统相册才会显示照片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html