我正在制作一个Node.js
带有图像处理的应用程序。我正在Jimp
用作图像处理库。我正在尝试根据参数(x、y、宽度、高度)制作虚线边框,并且我目前正在尝试使边框变为上、右、下、左。在左侧和底部边框上,我需要反转扫描,但我无法给出负数作为scanQuiet
. 有什么办法可以解决我的问题吗?
代码:
const Jimp = require("jimp");
function dashedBorder(
image,
{ lineDash, lineWidth, color },
{ x, y, width, height }
) {
let drawing = true,
passed = 0,
offset = lineWidth - 1;
color = Jimp.intToRGBA(color);
// Top border
image.scanQuiet(x - offset, y - offset, width, 1, (x, y) => {
if (drawing) {
const pixelColor = Jimp.intToRGBA(image.getPixelColor(x, y));
const newColor = blendColors(pixelColor, color);
for (let i = 0; i < lineWidth; i++) {
image.setPixelColor(
Jimp.rgbaToInt(newColor.r, newColor.g, newColor.b, 255),
x,
y + i
);
}
}
passed++;
if (
(passed >= lineDash[0] && drawing) ||
(passed >= lineDash[1] && !drawing)
) {
drawing = !drawing;
passed = 0;
}
});
drawing = true;
// Right border
image.scanQuiet(
x + width + offset,
y + lineWidth + offset,
1,
height - lineWidth * 2,
(x, y) => {
if (drawing) {
const pixelColor = Jimp.intToRGBA(image.getPixelColor(x, y));
const newColor = blendColors(pixelColor, color);
for (let i = 0; i < lineWidth; i++) {
image.setPixelColor(
Jimp.rgbaToInt(newColor.r, newColor.g, newColor.b, 255),
x - i,
y
);
}
}
passed++;
if (
(passed >= lineDash[0] && drawing) ||
(passed >= lineDash[1] && !drawing)
) {
drawing = !drawing;
passed = 0;
}
}
);
drawing = true;
// Bottom border
image.scanQuiet(
x + width + offset,
y + height + offset,
-width,
-1,
(x, y) => {
if (drawing) {
const pixelColor = Jimp.intToRGBA(image.getPixelColor(x, y));
const newColor = blendColors(pixelColor, color);
for (let i = 0; i < lineWidth; i++) {
image.setPixelColor(
Jimp.rgbaToInt(newColor.r, newColor.g, newColor.b, 255),
x,
y - i
);
}
}
passed++;
if (
(passed >= lineDash[0] && drawing) ||
(passed >= lineDash[1] && !drawing)
) {
drawing = !drawing;
passed = 0;
}
}
);
drawing = true;
// Left border
image.scanQuiet(
x - offset,
y + height - lineWidth - offset,
1,
-height + lineWidth * 2,
(x, y) => {
if (drawing) {
const pixelColor = Jimp.intToRGBA(image.getPixelColor(x, y));
const newColor = blendColors(pixelColor, color);
for (let i = 0; i < lineWidth; i++) {
image.setPixelColor(
Jimp.rgbaToInt(newColor.r, newColor.g, newColor.b, 255),
x + i,
y
);
}
}
passed++;
if (
(passed >= lineDash[0] && drawing) ||
(passed >= lineDash[1] && !drawing)
) {
drawing = !drawing;
passed = 0;
}
}
);
}
function blendColors(c1, c2) {
const stepPoint = c2.a / 255;
const r = c1.r + stepPoint * (c2.r - c1.r);
const g = c1.g + stepPoint * (c2.g - c1.g);
const b = c1.b + stepPoint * (c2.b - c1.b);
return { r, g, b };
}
(async () => {
let image = await Jimp.read("./test.png");
dashedBorder(
image,
{ lineWidth: 3, lineDash: [20, 5], color: 0x1a53ffbb },
{ x: 0, y: 0, width: image.bitmap.width, height: image.bitmap.height }
);
image.write("./test-border.png");
})();