HarmonyOS鸿蒙Next中网页base64图片如何保存至相册?
HarmonyOS鸿蒙Next中网页base64图片如何保存至相册? 网页不方便使用SaveButton安全控件,如何将base64图片保存至相册?
鸿蒙系统中针对网页保存图片场景,提供了ohos.permission.SHORT_TERM_WRITE_IMAGEVIDEO受限开放权限可以使用,保存图片,
- 首先在module.json5中添加权限:
{
"name": "ohos.permission.SHORT_TERM_WRITE_IMAGEVIDEO",
"reason": "$string:Write_ImageVideo_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
如果使用调试生产证书,则需要申请受限权限,申请方式:http://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/declare-permissions-in-acl-V5
- 示例代码,下方代码在ets中模拟场景,将网页图片的base64字符串传进来,既可以完成保存至相册。
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { util } from '@kit.ArkTS';
@Entry
@Component
struct Index {
private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
@Styles
butStyle(){
.width(200)
.height(50)
}
async saveImageToAlbum() {
let base64Image: string = ''
let photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
title: '123456',
fileNameExtension: 'jpg',
photoType: photoAccessHelper.PhotoType.IMAGE,
subtype: photoAccessHelper.PhotoSubtype.DEFAULT,
};
try {
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
let resultUri: string = await phAccessHelper.createAssetWithShortTermPermission(photoCreationConfig);
let file: fileIo.File = fileIo.openSync(resultUri, fileIo.OpenMode.READ_WRITE);
// 写入文件
let imageBuffer: ArrayBuffer = await this.base64ToArrayBuffer(base64Image)
await fileIo.write(file.fd, imageBuffer);
// 关闭文件
await fileIo.close(file.fd);
} catch (error) {
console.error("error is " + JSON.stringify(error))
}
}
async base64ToArrayBuffer(base64Str: string): Promise<ArrayBuffer> {
let base64 = new util.Base64Helper();
let uint8Array: Uint8Array = await base64.decode(base64Str)
let buffer: ArrayBuffer = uint8Array.buffer.slice(0, uint8Array.byteLength)
return buffer
}
build() {
Column() {
Button("下载base64图片到相册", { type: ButtonType.Capsule, stateEffect: false })
.fontSize('15fp')
.fontColor('#ffffff')
.butStyle()
.onClick(() => {
this.saveImageToAlbum()
})
}
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
更多关于HarmonyOS鸿蒙Next中网页base64图片如何保存至相册?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,将网页中的Base64图片保存至相册可以通过以下步骤实现:
-
解析Base64数据:首先,需要将Base64字符串解码为二进制数据。可以使用
Base64类提供的解码方法。 -
创建图片文件:将解码后的二进制数据写入到一个临时文件中,生成图片文件。
-
保存至相册:使用
MediaStoreAPI,将生成的图片文件保存到设备的相册中。需要申请相应的存储权限。
具体代码示例如下:
import { Base64 } from '@ohos.base64';
import { MediaStore } from '@ohos.multimedia.mediaLibrary';
import { fileIo } from '@ohos.fileio';
async function saveBase64ToGallery(base64Str: string) {
// 解析Base64数据
const binaryData = Base64.decode(base64Str);
// 创建临时文件
const tempFilePath = '临时文件路径';
await fileIo.writeFile(tempFilePath, binaryData);
// 保存至相册
const mediaStore = new MediaStore.MediaLibrary();
const mediaFile = await mediaStore.createMediaFile(tempFilePath, MediaStore.MediaType.IMAGE);
await mediaStore.addMediaToAlbum(mediaFile);
}
确保在调用此功能前,已在应用的config.json中声明了ohos.permission.WRITE_MEDIA权限。
在HarmonyOS鸿蒙Next中,将网页中的Base64图片保存至相册可以通过以下步骤实现:
- 解码Base64:将Base64字符串解码为字节数组。
- 创建文件:在应用的缓存目录中创建一个临时文件,并将字节数组写入该文件。
- 保存至相册:使用
MediaStoreAPI将临时文件保存至相册。
代码示例:
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.member.MediaStoreHelper;
String base64 = "your_base64_string";
byte[] imageData = Base64.decode(base64, Base64.DEFAULT);
File tempFile = new File(context.getCacheDir(), "temp_image.jpg");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(imageData);
fos.close();
MediaStoreHelper.saveImageToMediaStore(context, tempFile.getAbsolutePath());
确保在config.json中添加必要的权限:
"reqPermissions": [
{"name": "ohos.permission.WRITE_MEDIA"}
]
通过以上步骤,Base64图片将被保存至相册。

