蓝瘦的蜕变ArkUI (方舟UI框架)
HarmonyOS 6
应用媒体
HarmonyOS 5
Ability (程序框架)
如何将Canvas绘制的资源以图片的形式保存至图库【案例示例】
1、自定义绘制的Canvas如何转为图片?
2、图片保存方案种类繁杂,申请各种权限成为您前进路上的绊脚石?


无需申请任何权限,即可完成。
实现步骤:
-
将Canvas组件赋予一个id,通过组件id截图的形式获取到对应的pixelMap;
-
通过SaveButton安全控件将pixelMap通过imagePackerApi.packToFile()这个API直接编写进文件即可。
-
ImagePacker:图片编码器类,用于图片压缩和编码。在调用ImagePacker的方法前,需要先通过createImagePacker构建一个ImagePacker实例。
-
SaveButton:安全控件的保存控件。应用集成保存控件后,用户首次使用保存控件展示弹窗,在点击允许后自动授权,应用会在短时间内获取访问媒体库特权接口的授权。后续使用无需弹窗授权。在API version 19及之前的版本中,授权持续时间为10秒;在API version20及之后的版本中,授权持续时间为1分钟。
真机效果:


关键代码:
1、id截图的形式获取到对应的pixelMap
@Local pixelMap?: image.PixelMap
private cvsID: string = 'canvasId'
//...
this.getUIContext().getComponentSnapshot().get(this.cvsID, (error: Error, pixmap: image.PixelMap) => {
}2、imagePackerApi.packToFile()将pixelMap编写进图库
imagePackerApi.packToFile(this.pixelMap, file.fd, packOpts, (err: BusinessError) => {
if (err) {
} else {
imagePackerApi.release((err: BusinessError) => {
if (err) {
} else {
fileIo.close(file.fd);
}
})
promptAction.showToast({ message: '已保存至相册!' });
}
})完整代码:
import { image } from "@kit.ImageKit";
import { common } from "@kit.AbilityKit";
import { photoAccessHelper } from "@kit.MediaLibraryKit";
import { fileIo } from "@kit.CoreFileKit";
import { promptAction } from "@kit.ArkUI";
import { BusinessError } from '@kit.BasicServicesKit';
@ComponentV2
export struct CanvasSaveImg {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
@Local pixelMap?: image.PixelMap
private cvsID: string = 'canvasId'
private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
build() {
Scroll() {
Column() {
Canvas(this.ctx)
.width(200)
.height(200)
.backgroundColor('#F5DC62')
.onReady(() => {
// 设定填充样式,填充颜色设为蓝色
this.ctx.fillStyle = '#ff7f27'
// 以(50, 50)为左上顶点,画一个宽高400的矩形B
this.ctx.fillRect(10, 10, 190, 190)
this.ctx.fillStyle = '#22b14c';
// 以(50, 50)为左上顶点,画一个宽高200的矩形A
this.ctx.fillRect(10, 10, 80, 80);
})
.id(this.cvsID)
Blank().height(30)
SaveButton({ text: SaveDescription.SAVE_IMAGE }).width('80%')
.onClick((event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
// 免去权限申请和权限请求等环节,获得临时授权,保存对应图片。
this.getUIContext().getComponentSnapshot().get(this.cvsID, (error: Error, pixmap: image.PixelMap) => {
this.pixelMap = pixmap;
this.savePixelMap();
});
} else {
promptAction.openToast({ message: '设置权限失败!' });
}
})
}.safeAreaPadding({ top: 30 })
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
async savePixelMap() {
// 获取相册的保存路径
let helper = photoAccessHelper.getPhotoAccessHelper(this.context);
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpeg');
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
let imagePackerApi = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };
imagePackerApi.packToFile(this.pixelMap, file.fd, packOpts, (err: BusinessError) => {
if (err) {
console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in packing the image to file.');
imagePackerApi.release((err: BusinessError) => {
if (err) {
console.error(`Failed to release the image source instance.code ${err.code},message is ${err.message}`);
} else {
console.info('Succeeded in releasing the image source instance.');
fileIo.close(file.fd);
}
})
promptAction.showToast({ message: '已保存至相册!' });
}
})
}
}组件引用
@Entry
@ComponentV2
struct Index {
build() {
Column() {
CanvasSaveImg()
}
.height('100%')
.width('100%')
}
}相关文档:
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
HarmonyOS Canvas绘制的线段模糊,不圆滑 (API12+)
HarmonyOS 一个UI组件能否通过Canvas绘制到另外一个UI上?(API12+)
HarmonyOS 怎么绘制条纹背景,用Canvas吗还是gradient(API12+)
HarmonyOS 是否可以将Canvas绘制内容放置到Bitmap上(API12+)
HarmonyOS CanvasRenderingContext2D绘制的内容如何保存成图片 (API12+)
HarmonyOS 如何将自定义组件转换成图片,保存到相册(API12+)
HarmonyOS 如何绘制一张自定义内容的图片并且按照指定的大小输出 (API12+)
渲染markdown文件




































苏公安网备 32011402010933号