Skip to content

Commit

Permalink
Add \n support for image.print(). This fixes jimp-dev#865
Browse files Browse the repository at this point in the history
  • Loading branch information
juurr00 committed Nov 1, 2023
1 parent af334ef commit 9dd782a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
14 changes: 7 additions & 7 deletions packages/plugin-print/src/measure-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,29 @@ export function measureText(font, text) {
}

export function splitLines(font, text, maxWidth) {
const words = text.split(" ");
const words = text.replace(/[\r\n]+/g, " \n").split(" ");

const lines = [];
let currentLine = [];
let longestLine = 0;

words.forEach((word) => {
const line = [...currentLine, word].join(" ");
const length = measureText(font, line);

if (length <= maxWidth) {
const withinMaxWidth = length <= maxWidth;
const containsNewline = word.includes("\n");

if (withinMaxWidth && !containsNewline) {
if (length > longestLine) {
longestLine = length;
}

currentLine.push(word);
} else {
lines.push(currentLine);
currentLine = [word];
currentLine = [word.replace("\n", "")];
}
});

lines.push(currentLine);

return {
lines,
longestLine,
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions packages/plugin-print/test/print.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,4 +294,17 @@ describe("Write text over image", function () {

expect(height).toEqual(lineHeight);
});

it("text with newlines, default alignment", async () => {
const expectedImage = await Jimp.read(
getTestDir(__dirname) + "/images/with-newlines.png"
);

const textImage = await createTextImage(100, 240, Jimp.FONT_SANS_16_BLACK, {
text: "This \nis only \na \ntest.",
maxWidth: 300,
});

expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data);
});
});

0 comments on commit 9dd782a

Please sign in to comment.