File size: 5,657 Bytes
3530df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { HorizontalAlign, VerticalAlign } from "@jimp/core";
import { JimpClass } from "@jimp/types";
import { methods as blitMethods } from "@jimp/plugin-blit";
import { z } from "zod";

import { measureText, measureTextHeight, splitLines } from "./measure-text.js";
import { BmCharacter, BmFont } from "./types.js";

export { measureText, measureTextHeight } from "./measure-text.js";
export * from "./types.js";

const PrintOptionsSchema = z.object({
  /** the x position to draw the image */
  x: z.number(),
  /** the y position to draw the image */
  y: z.number(),
  /** the text to print */
  text: z.union([
    z.union([z.string(), z.number()]),
    z.object({
      text: z.union([z.string(), z.number()]),
      alignmentX: z.nativeEnum(HorizontalAlign).optional(),
      alignmentY: z.nativeEnum(VerticalAlign).optional(),
    }),
  ]),
  /** the boundary width to draw in */
  maxWidth: z.number().optional(),
  /** the boundary height to draw in */
  maxHeight: z.number().optional(),
  /** a callback for when complete that ahs the end co-ordinates of the text */
  cb: z
    .function(z.tuple([z.object({ x: z.number(), y: z.number() })]))
    .optional(),
});

export type PrintOptions = z.infer<typeof PrintOptionsSchema>;

function xOffsetBasedOnAlignment<I extends JimpClass>(
  font: BmFont<I>,
  line: string,
  maxWidth: number,
  alignment: HorizontalAlign
) {
  if (alignment === HorizontalAlign.LEFT) {
    return 0;
  }

  if (alignment === HorizontalAlign.CENTER) {
    return (maxWidth - measureText(font, line)) / 2;
  }

  return maxWidth - measureText(font, line);
}

function drawCharacter<I extends JimpClass>(
  image: I,
  font: BmFont<I>,
  x: number,
  y: number,
  char: BmCharacter
) {
  if (char.width > 0 && char.height > 0) {
    const characterPage = font.pages[char.page];

    if (characterPage) {
      image = blitMethods.blit(image, {
        src: characterPage,
        x: x + char.xoffset,
        y: y + char.yoffset,
        srcX: char.x,
        srcY: char.y,
        srcW: char.width,
        srcH: char.height,
      });
    }
  }

  return image;
}

function printText<I extends JimpClass>(
  image: I,
  font: BmFont<I>,
  x: number,
  y: number,
  text: string,
  defaultCharWidth: number
) {
  for (let i = 0; i < text.length; i++) {
    const stringChar = text[i]!;

    let char;

    if (font.chars[stringChar]) {
      char = stringChar;
    } else if (/\s/.test(stringChar)) {
      char = "";
    } else {
      char = "?";
    }

    const fontChar = font.chars[char] || { xadvance: undefined };
    const fontKerning = font.kernings[char];

    if (fontChar) {
      drawCharacter(image, font, x, y, fontChar as BmCharacter);
    }

    const nextChar = text[i + 1];
    const kerning =
      fontKerning && nextChar && fontKerning[nextChar]
        ? fontKerning[nextChar] || 0
        : 0;

    x += kerning + (fontChar.xadvance || defaultCharWidth);
  }
}

export const methods = {
  /**
   * Draws a text on a image on a given boundary
   * @param font a bitmap font loaded from `Jimp.loadFont` command
   * @param x the x position to start drawing the text
   * @param y the y position to start drawing the text
   * @param text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`)
   * @example
   * ```ts
   * import { Jimp } from "jimp";
   *
   * const image = await Jimp.read("test/image.png");
   * const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
   *
   * image.print({ font, x: 10, y: 10, text: "Hello world!" });
   * ```
   */
  print<I extends JimpClass>(
    image: I,
    {
      font,
      ...options
    }: PrintOptions & {
      /** the BMFont instance */
      font: BmFont<I>;
    }
  ) {
    let {
      // eslint-disable-next-line prefer-const
      x,
      y,
      text,
      // eslint-disable-next-line prefer-const
      maxWidth = Infinity,
      // eslint-disable-next-line prefer-const
      maxHeight = Infinity,
      // eslint-disable-next-line prefer-const
      cb = () => {},
    } = PrintOptionsSchema.parse(options);

    let alignmentX: HorizontalAlign;
    let alignmentY: VerticalAlign;

    if (
      typeof text === "object" &&
      text.text !== null &&
      text.text !== undefined
    ) {
      alignmentX = text.alignmentX || HorizontalAlign.LEFT;
      alignmentY = text.alignmentY || VerticalAlign.TOP;
      ({ text } = text);
    } else {
      alignmentX = HorizontalAlign.LEFT;
      alignmentY = VerticalAlign.TOP;
      text = text.toString();
    }

    if (typeof text === "number") {
      text = text.toString();
    }

    if (maxHeight !== Infinity && alignmentY === VerticalAlign.BOTTOM) {
      y += maxHeight - measureTextHeight(font, text, maxWidth);
    } else if (maxHeight !== Infinity && alignmentY === VerticalAlign.MIDDLE) {
      y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2;
    }

    const defaultCharWidth = Object.entries(font.chars).find(
      (c) => c[1].xadvance
    )?.[1].xadvance;

    if (typeof defaultCharWidth !== "number") {
      throw new Error("Could not find default character width");
    }

    const { lines, longestLine } = splitLines(font, text, maxWidth);

    lines.forEach((line) => {
      const lineString = line.join(" ");
      const alignmentWidth = xOffsetBasedOnAlignment(
        font,
        lineString,
        maxWidth,
        alignmentX
      );

      printText(
        image,
        font,
        x + alignmentWidth,
        y,
        lineString,
        defaultCharWidth
      );
      y += font.common.lineHeight;
    });

    cb.bind(image)({ x: x + longestLine, y });

    return image;
  },
};