HarmonyOS鸿蒙Next中是否有接口把image.PixelMap对象的背景色变为白色
HarmonyOS鸿蒙Next中是否有接口把image.PixelMap对象的背景色变为白色 canvas返回的image.PixelMap对象的背景色是透明的,这边需要把背景色处理为白色,根据官方的图像处理那块的说明,这边可以通过修改图像的ArrayBuffer实现,不过实际测试,效率非常低,不知官方是否有提供API实现?
可以在拿到组件转成的pixelmap后,read出来,再把read出的buf遍历修改,最后把修改后的写回pixelmap或者创建新的pixelmap。
参考如下:
import { image } from '@kit.ImageKit'
import fs from '@ohos.file.fs'
import display from '@ohos.display';
import drawing from "@ohos.graphics.drawing";
import { BusinessError } from '@kit.BasicServicesKit';
let screen = display.getDefaultDisplaySync();
let screenWidth: number = screen.width;
let screenHeight: number = screen.height;
let canvas_: drawing.Canvas;
let pixelMap_: image.PixelMap | undefined;
const TAG = 'DrawingTSSample';
@Entry
@Component
struct CreateLinearGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
handleClick = async () => {
const offCanvas = new OffscreenCanvas(this.context.width, this.context.height);
const offCtx = offCanvas.getContext("2d");
this.CreateBitmapCanvas();
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("hello").onClick(() => {
this.handleClick();
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(async () => {
// this.CreateBitmapCanvas();
let grad = this.context.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, '#FF0000')
grad.addColorStop(1, '#0000FF')
this.context.fillStyle = grad
// Create path
let region = new Path2D();
region.rect(10, 10, 150, 75)
region.closePath();
this.context.fill(region);
})
}
.width('100%')
.height('100%')
}
public async CreateBitmapCanvas() {
const color: ArrayBuffer = new ArrayBuffer(screenHeight * screenWidth * 4);
const imageData = new Uint8ClampedArray(color);
let opts: image.InitializationOptions =
{ editable: true, pixelFormat: 3, size: { height: screenHeight, width: screenWidth } };
// 创建一个Uint8ClampedArray来存储像素数据
for (let i = 0; i < screenHeight * screenWidth; i++) {
// BGRA
const offset = i * 4;
imageData[offset] = 0; //
imageData[offset + 1] = 255; //
imageData[offset + 2] = 255; //
imageData[offset + 3] = 0; //
}
console.log(TAG, 'screenHeight*screenWidth=' + screenHeight + '---' + screenWidth);
pixelMap_ = await image.createPixelMap(color, opts);
if (pixelMap_ === null || pixelMap_ === undefined) {
console.log(TAG, 'create pixelMap error');
return;
}
// 创建离屏canvas,与pixelMap绑定
canvas_ = new drawing.Canvas(pixelMap_);
if (canvas_ === null || canvas_ === undefined) {
console.log(TAG, 'create canvas_ error');
return;
}
console.log(TAG, 'create canvas_ success');
// 调用自定义函数绘制
drawCase(canvas_);
const ctx = getContext(this);
const tmp = `${ctx.tempDir}/1.jpg`;
const file = fs.openSync(tmp, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
// let pixmap = offCtx.getPixelMap(0,0,300,300);
// 放缩到目标宽高
// Android 的 pixmap 有 scalemap 本质上就是这个实现
await pixelMap_.scale(1, 1);
const imagePickerApi = image.createImagePacker();
await imagePickerApi.packToFile(pixelMap_, file.fd, {
quality: 50,
format: "image/jpeg",
});
pixelMap_.release();
imagePickerApi.release();
}
}
async function drawCase(canvas: drawing.Canvas) {
let pen = new drawing.Pen();
pen.setStrokeWidth(5);
pen.setColor({
alpha: 255,
red: 255,
green: 255,
blue: 0
});
canvas.attachPen(pen);
canvas.drawRect({
left: 200,
right: 500,
top: 50,
bottom: 300
});
canvas.detachPen();
}
更多关于HarmonyOS鸿蒙Next中是否有接口把image.PixelMap对象的背景色变为白色的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,可以通过PixelMap类的eraseColor方法将PixelMap对象的背景色设置为白色。具体实现如下:
import image from '@ohos.multimedia.image';
let pixelMap: image.PixelMap;
pixelMap.eraseColor(0xFFFFFFFF); // 0xFFFFFFFF 表示白色
eraseColor方法的参数是一个表示颜色的32位整数,格式为ARGB(Alpha, Red, Green, Blue)。0xFFFFFFFF表示完全不透明的白色。调用此方法后,PixelMap对象的背景色将被设置为白色。
在HarmonyOS鸿蒙Next中,可以通过PixelMap的replaceColor方法来实现将背景色替换为白色。首先,获取当前背景颜色,然后使用replaceColor方法将背景色替换为白色。具体代码示例如下:
PixelMap pixelMap = ...; // 获取PixelMap对象
int backgroundColor = pixelMap.getPixel(0, 0); // 获取背景色
pixelMap.replaceColor(backgroundColor, Color.WHITE); // 替换为白色
此方法会遍历所有像素并将原背景色替换为白色。

