OpenHarmony图形图像实现图像编辑
一 核心思路与流程
二 环境准备与权限配置
三 关键实现步骤与代码示例
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import { getContext } from '@ohos.app.ability.common';
async function getPixelMapFromResource(resName: string): Promise<image.PixelMap> {
const ctx = getContext(this) as common.UIAbilityContext;
const resMgr = ctx.resourceManager;
const fileData = await resMgr.getMediaContent($r(`app.media.${resName}`));
const buffer = fileData.buffer;
const imageSource = image.createImageSource(buffer);
return await imageSource.createPixelMap({ editable: true }); // 可编辑
}
// 裁剪
await pixelMap.crop({ x: 0, y: 0, size: { width: 300, height: 300 } });
// 缩放
await pixelMap.scale(0.5, 0.5);
// 旋转(角度制)
await pixelMap.rotate(90);
// 翻转:水平 false、垂直 true
await pixelMap.flip(false, true);
// 透明度(0.0 ~ 1.0)
await pixelMap.opacity(0.8);
// workers/adjustBrightnessWork.ts
import image from '@ohos.multimedia.image';
export function adjustBrightness(pixelMap: image.PixelMap, brightness: number): image.PixelMap {
// 读取像素、按 brightness 调整(示例略)
// 返回新的 PixelMap
return pixelMap;
}
// ArkTS UI 回显
Image(this.editedPixelMap).objectFit(ImageFit.Contain).width('100%').height('80%');
// 编码为 PNG 并保存
import { util } from '@ohos.util';
async function savePixelMap(pixelMap: image.PixelMap, fileName: string) {
const ctx = getContext(this) as common.UIAbilityContext;
const encoder = image.createImagePacker();
const data = await encoder.packToData(pixelMap, { format: 'image/png', quality: 100 });
const filePath = `${ctx.cacheDir}/${fileName}`;
const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, data.buffer);
fs.closeSync(file.fd);
}
// 获取 Canvas 2D 上下文并绘制
const canvas = this.$element('canvasOne') as HTMLCanvasElement;
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(pixelMap, 0, 0, canvas.width, canvas.height);
以上流程与 API 在 ArkTS/JS 项目中均适用,裁剪、旋转、缩放、翻转、透明度等方法为 PixelMap 常用编辑接口;像素级调节建议放入 Worker 执行。
四 性能与体验优化
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。