Spaces:
Sleeping
Sleeping
File size: 21,704 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 | import { Bitmap, Format, JimpClass, Edge } from "@jimp/types";
import { cssColorToHex, scan, scanIterator } from "@jimp/utils";
import { to } from "await-to-js";
import { existsSync, readFile, writeFile } from "@jimp/file-ops";
import mime from "mime/lite.js";
import { composite } from "./utils/composite.js";
import { BlendMode } from "./index.js";
import { attemptExifRotate } from "./utils/image-bitmap.js";
const emptyBitmap: Bitmap = {
data: Buffer.alloc(0),
width: 0,
height: 0,
};
/**
* Prepare a Buffer object from the arrayBuffer.
*/
function bufferFromArrayBuffer(arrayBuffer: ArrayBuffer) {
const buffer = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = view[i]!;
}
return buffer;
}
async function detectFileTypeFromBuffer(buffer: Buffer | ArrayBuffer) {
const { fileTypeFromBuffer } = await import("file-type");
return fileTypeFromBuffer(
buffer instanceof ArrayBuffer
? buffer
: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
);
}
export { getExifOrientation } from "./utils/image-bitmap.js";
export { composite } from "./utils/composite.js";
export * from "./utils/constants.js";
export interface RawImageData {
width: number;
height: number;
data: Buffer | Uint8Array | Uint8ClampedArray | number[];
}
/**
* Instead of loading an image into an instance you can initialize a new Jimp instance with a empty bitmap.
*/
export interface JimpSimpleConstructorOptions {
height: number;
width: number;
/**
* Initialize the image with a color for each pixel
*/
color?: number | string;
}
export type JimpConstructorOptions = Bitmap | JimpSimpleConstructorOptions;
/** Converts a jimp plugin function to a Jimp class method */
type JimpInstanceMethod<ClassInstance, MethodMap, Method> =
Method extends JimpChainableMethod<infer Args>
? (
...args: Args
) => JimpInstanceMethods<ClassInstance, MethodMap> & ClassInstance
: Method extends JimpMethod<infer Args, infer Return>
? (...args: Args) => Return
: never;
/** Converts a Record of jimp plugin functions to a Record of Jimp class methods */
export type JimpInstanceMethods<ClassInstance, MethodMap> = {
[Key in keyof MethodMap]: JimpInstanceMethod<
ClassInstance,
MethodMap,
MethodMap[Key]
>;
};
/** A Jimp instance method that can be chained. */
type JimpChainableMethod<
Args extends any[] = any[],
J extends JimpClass = JimpClass,
> = (img: J, ...args: Args) => J;
/** A Jimp instance method that returns anything. */
type JimpMethod<
Args extends any[] = any[],
ReturnType = any,
J extends JimpClass = JimpClass,
> = (img: J, ...args: Args) => ReturnType;
export interface JimpPlugin {
[key: string]: JimpChainableMethod | JimpMethod;
}
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;
type Constructor<T> = new (...args: any[]) => T;
type JimpFormat<
MimeType extends string = string,
EncodeOptions extends Record<string, any> | undefined = undefined,
DecodeOptions extends Record<string, any> | undefined = undefined,
T extends Format<MimeType, EncodeOptions, DecodeOptions> = Format<
MimeType,
EncodeOptions,
DecodeOptions
>,
> = () => T;
type CreateMimeTypeToExportOptions<T extends Format<string, any>> =
T extends Format<infer M, infer O> ? Record<M, O> : never;
type CreateMimeTypeToDecodeOptions<T extends Format<string, any>> =
T extends Format<infer M, any, infer O> ? Record<M, O> : never;
type GetOptionsForMimeType<Mime extends string, MimeTypeMap> =
MimeTypeMap extends Record<Mime, infer O> ? O : never;
type PathWithExtension<E extends string> = `${string}.${E}`;
type MimeToExtension<M extends string> = `${string}/${M}`;
type CreateExtensionToMimeType<M extends string> =
M extends MimeToExtension<infer E> ? Record<E, M> : never;
type GetMimeTypeForExtension<Mime extends string, MimeTypeMap> =
MimeTypeMap extends Record<Mime, infer M> ? M : never;
/**
* Create a Jimp class that support the given image formats and methods
*/
export function createJimp<
Methods extends JimpPlugin[],
Formats extends JimpFormat[],
>({
plugins: pluginsArg,
formats: formatsArg,
}: {
/** Plugins that add methods to the created Jimp class */
plugins?: Methods;
/** Image formats the Jimp class should support */
formats?: Formats;
} = {}) {
type ExtraMethodMap = JimpInstanceMethods<
InstanceType<typeof CustomJimp>,
UnionToIntersection<Methods[number]>
>;
type SupportedMimeTypes = ReturnType<Formats[number]>["mime"];
type MimeTypeToExportOptions = CreateMimeTypeToExportOptions<
ReturnType<Formats[number]>
>;
type MimeTypeToDecodeOptions = CreateMimeTypeToDecodeOptions<
ReturnType<Formats[number]>
>;
type ExtensionToMimeType = CreateExtensionToMimeType<SupportedMimeTypes>;
const plugins = pluginsArg || [];
const formats = (formatsArg || []).map((format) => format());
const CustomJimp = class Jimp implements JimpClass {
/**
* The bitmap data of the image
*/
bitmap: Bitmap = emptyBitmap;
/** Default color to use for new pixels */
background = 0x00000000;
/** Formats that can be used with Jimp */
formats: Format<any>[] = [];
/** The original MIME type of the image */
mime?: string;
constructor(options: JimpConstructorOptions = emptyBitmap) {
// Add the formats
this.formats = formats;
if ("data" in options) {
this.bitmap = options;
} else {
this.bitmap = {
data: Buffer.alloc(options.width * options.height * 4),
width: options.width,
height: options.height,
};
if (options.color) {
this.background =
typeof options.color === "string"
? cssColorToHex(options.color)
: options.color;
for (let i = 0; i < this.bitmap.data.length; i += 4) {
this.bitmap.data.writeUInt32BE(this.background, i);
}
}
}
// Add the plugins
for (const methods of plugins) {
for (const key in methods) {
(this as any)[key] = (...args: any[]) => {
const result = methods[key]?.(this, ...args);
if (typeof result === "object" && "bitmap" in result) {
this.bitmap = result.bitmap;
return this;
}
return result;
};
}
}
}
/**
* Create a Jimp instance from a URL, a file path, or a Buffer
* @example
* ```ts
* import { Jimp } from "jimp";
*
* // Read from a file path
* const image = await Jimp.read("test/image.png");
*
* // Read from a URL
* const image = await Jimp.read("https://upload.wikimedia.org/wikipedia/commons/0/01/Bot-Test.jpg");
* ```
*/
static async read(
url: string | Buffer | ArrayBuffer,
options?: MimeTypeToDecodeOptions
) {
if (Buffer.isBuffer(url) || url instanceof ArrayBuffer) {
return this.fromBuffer(url);
}
if (existsSync(url)) {
return this.fromBuffer(await readFile(url));
}
const [fetchErr, response] = await to(fetch(url));
if (fetchErr) {
throw new Error(`Could not load Buffer from URL: ${url}`);
}
if (!response.ok) {
throw new Error(`HTTP Status ${response.status} for url ${url}`);
}
const [arrayBufferErr, data] = await to(response.arrayBuffer());
if (arrayBufferErr) {
throw new Error(`Could not load Buffer from ${url}`);
}
const buffer = bufferFromArrayBuffer(data);
return this.fromBuffer(buffer, options);
}
/**
* Create a Jimp instance from a bitmap.
* The difference between this and just using the constructor is that this will
* convert raw image data into the bitmap format that Jimp uses.
*
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = Jimp.fromBitmap({
* data: Buffer.from([
* 0xffffffff, 0xffffffff, 0xffffffff,
* 0xffffffff, 0xffffffff, 0xffffffff,
* 0xffffffff, 0xffffffff, 0xffffffff,
* ]),
* width: 3,
* height: 3,
* });
* ```
*/
static fromBitmap(bitmap: RawImageData) {
let data: Buffer | undefined;
if (bitmap.data instanceof Buffer) {
data = Buffer.from(bitmap.data);
}
if (
bitmap.data instanceof Uint8Array ||
bitmap.data instanceof Uint8ClampedArray
) {
data = Buffer.from(bitmap.data.buffer);
}
if (Array.isArray(bitmap.data)) {
data = Buffer.concat(
bitmap.data.map((hex) =>
Buffer.from(hex.toString(16).padStart(8, "0"), "hex")
)
);
}
if (!data) {
throw new Error("data must be a Buffer");
}
if (
typeof bitmap.height !== "number" ||
typeof bitmap.width !== "number"
) {
throw new Error("bitmap must have width and height");
}
return new CustomJimp({
height: bitmap.height,
width: bitmap.width,
data,
}) as InstanceType<typeof CustomJimp> & ExtraMethodMap;
}
/**
* Parse a bitmap with the loaded image types.
*
* @param buffer Raw image data
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const buffer = await fs.readFile("test/image.png");
* const image = await Jimp.fromBuffer(buffer);
* ```
*/
static async fromBuffer(
buffer: Buffer | ArrayBuffer,
options?: MimeTypeToDecodeOptions
) {
const actualBuffer =
buffer instanceof ArrayBuffer ? bufferFromArrayBuffer(buffer) : buffer;
const mime = await detectFileTypeFromBuffer(actualBuffer);
if (!mime || !mime.mime) {
throw new Error("Could not find MIME for Buffer");
}
const format = formats.find((format) => format.mime === mime.mime);
if (!format || !format.decode) {
throw new Error(`Mime type ${mime.mime} does not support decoding`);
}
const image = new CustomJimp(
await format.decode(actualBuffer, options?.[format.mime])
) as InstanceType<typeof CustomJimp> & ExtraMethodMap;
image.mime = mime.mime;
attemptExifRotate(image, actualBuffer);
return image;
}
/**
* Nicely format Jimp object when sent to the console e.g. console.log(image)
* @returns Pretty printed jimp object
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = await Jimp.read("test/image.png");
*
* console.log(image);
* ```
*/
inspect() {
return (
"<Jimp " +
(this.bitmap === emptyBitmap
? "pending..."
: this.bitmap.width + "x" + this.bitmap.height) +
">"
);
}
/**
* Nicely format Jimp object when converted to a string
* @returns pretty printed
*/
toString() {
return "[object Jimp]";
}
/** Get the width of the image */
get width() {
return this.bitmap.width;
}
/** Get the height of the image */
get height() {
return this.bitmap.height;
}
/**
* Converts the Jimp instance to an image buffer
* @param mime The mime type to export to
* @param options The options to use when exporting
* @example
* ```ts
* import { Jimp } from "jimp";
* import { promises as fs } from "fs";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* await image.getBuffer("image/jpeg", {
* quality: 50,
* });
* ```
*/
async getBuffer<
ProvidedMimeType extends SupportedMimeTypes,
Options extends GetOptionsForMimeType<
ProvidedMimeType,
MimeTypeToExportOptions
>,
>(mime: ProvidedMimeType, options?: Options) {
const format = this.formats.find((format) => format.mime === mime);
if (!format || !format.encode) {
throw new Error(`Unsupported MIME type: ${mime}`);
}
let outputImage: Jimp;
if (format.hasAlpha) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
outputImage = this;
} else {
outputImage = new CustomJimp({
width: this.bitmap.width,
height: this.bitmap.height,
color: this.background,
});
composite(outputImage, this);
}
return format.encode(outputImage.bitmap, options);
}
/**
* Converts the image to a base 64 string
*
* @param mime The mime type to export to
* @param options The options to use when exporting
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = Jimp.fromBuffer(Buffer.from([
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* ]));
*
* const base64 = image.getBase64("image/jpeg", {
* quality: 50,
* });
* ```
*/
async getBase64<
ProvidedMimeType extends SupportedMimeTypes,
Options extends GetOptionsForMimeType<
ProvidedMimeType,
MimeTypeToExportOptions
>,
>(mime: ProvidedMimeType, options?: Options) {
const data = await this.getBuffer(mime, options);
return "data:" + mime + ";base64," + data.toString("base64");
}
/**
* Write the image to a file
* @param path the path to write the image to
* @param options the options to use when writing the image
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = Jimp.fromBuffer(Buffer.from([
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
* ]));
*
* await image.write("test/output.png");
* ```
*/
async write<
Extension extends string,
Mime extends GetMimeTypeForExtension<Extension, ExtensionToMimeType>,
Options extends GetOptionsForMimeType<Mime, MimeTypeToExportOptions>,
>(path: PathWithExtension<Extension>, options?: Options) {
const mimeType = mime.getType(path);
await writeFile(
path,
await this.getBuffer(mimeType as SupportedMimeTypes, options)
);
}
/**
* Clone the image into a new Jimp instance.
* @param this
* @returns A new Jimp instance
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* const clone = image.clone();
* ```
*/
clone<S extends typeof CustomJimp>(this: S) {
return new CustomJimp({
...(this as any).bitmap,
data: Buffer.from((this as any).bitmap.data),
}) as unknown as S;
}
/**
* Returns the offset of a pixel in the bitmap buffer
* @param x the x coordinate
* @param y the y coordinate
* @param edgeHandling (optional) define how to sum pixels from outside the border
* @returns the index of the pixel or -1 if not found
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* image.getPixelIndex(1, 1); // 2
* ```
*/
getPixelIndex(x: number, y: number, edgeHandling?: Edge) {
let xi;
let yi;
if (!edgeHandling) {
edgeHandling = Edge.EXTEND;
}
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
// round input
x = Math.round(x);
y = Math.round(y);
xi = x;
yi = y;
if (edgeHandling === Edge.EXTEND) {
if (x < 0) xi = 0;
if (x >= this.bitmap.width) xi = this.bitmap.width - 1;
if (y < 0) yi = 0;
if (y >= this.bitmap.height) yi = this.bitmap.height - 1;
}
if (edgeHandling === Edge.WRAP) {
if (x < 0) {
xi = this.bitmap.width + x;
}
if (x >= this.bitmap.width) {
xi = x % this.bitmap.width;
}
if (y < 0) {
yi = this.bitmap.height + y;
}
if (y >= this.bitmap.height) {
yi = y % this.bitmap.height;
}
}
let i = (this.bitmap.width * yi + xi) << 2;
// if out of bounds index is -1
if (xi < 0 || xi >= this.bitmap.width) {
i = -1;
}
if (yi < 0 || yi >= this.bitmap.height) {
i = -1;
}
return i;
}
/**
* Returns the hex color value of a pixel
* @param x the x coordinate
* @param y the y coordinate
* @returns the color of the pixel
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* image.getPixelColor(1, 1); // 0xffffffff
* ```
*/
getPixelColor(x: number, y: number) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
const idx = this.getPixelIndex(x, y);
return this.bitmap.data.readUInt32BE(idx);
}
/**
* Sets the hex colour value of a pixel
*
* @param hex color to set
* @param x the x coordinate
* @param y the y coordinate
*
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* image.setPixelColor(0xff0000ff, 0, 0);
* ```
*/
setPixelColor(hex: number, x: number, y: number) {
if (
typeof hex !== "number" ||
typeof x !== "number" ||
typeof y !== "number"
) {
throw new Error("hex, x and y must be numbers");
}
const idx = this.getPixelIndex(x, y);
this.bitmap.data.writeUInt32BE(hex, idx);
return this;
}
/**
* Determine if the image contains opaque pixels.
*
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffaa });
* const image2 = new Jimp({ width: 3, height: 3, color: 0xff0000ff });
*
* image.hasAlpha(); // false
* image2.hasAlpha(); // true
* ```
*/
hasAlpha() {
const { width, height, data } = this.bitmap;
const byteLen = (width * height) << 2;
for (let idx = 3; idx < byteLen; idx += 4) {
if (data[idx] !== 0xff) {
return true;
}
}
return false;
}
/**
* Composites a source image over to this image respecting alpha channels
* @param src the source Jimp instance
* @param x the x position to blit the image
* @param y the y position to blit the image
* @param options determine what mode to use
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 10, height: 10, color: 0xffffffff });
* const image2 = new Jimp({ width: 3, height: 3, color: 0xff0000ff });
*
* image.composite(image2, 3, 3);
* ```
*/
composite<I extends typeof this>(
src: I,
x = 0,
y = 0,
options: {
mode?: BlendMode;
opacitySource?: number;
opacityDest?: number;
} = {}
) {
return composite(this, src, x, y, options);
}
/**
* Scan through the image and call the callback for each pixel
*
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* image.scan((x, y, idx) => {
* // do something with the pixel
* });
*
* // Or scan through just a region
* image.scan(0, 0, 2, 2, (x, y, idx) => {
* // do something with the pixel
* });
* ```
*/
scan(f: (x: number, y: number, idx: number) => any): this;
scan(
x: number,
y: number,
w: number,
h: number,
cb: (x: number, y: number, idx: number) => any
): this;
scan(
x: number | ((x: number, y: number, idx: number) => any),
y?: number,
w?: number,
h?: number,
f?: (x: number, y: number, idx: number) => any
): this {
return scan(this, x as any, y as any, w as any, h as any, f as any);
}
/**
* Iterate scan through a region of the bitmap
* @param x the x coordinate to begin the scan at
* @param y the y coordinate to begin the scan at
* @param w the width of the scan region
* @param h the height of the scan region
* @example
* ```ts
* import { Jimp } from "jimp";
*
* const image = new Jimp({ width: 3, height: 3, color: 0xffffffff });
*
* for (const { x, y, idx, image } of j.scanIterator()) {
* // do something with the pixel
* }
* ```
*/
scanIterator(x = 0, y = 0, w = this.bitmap.width, h = this.bitmap.height) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers");
}
if (typeof w !== "number" || typeof h !== "number") {
throw new Error("w and h must be numbers");
}
return scanIterator(this, x, y, w, h);
}
};
return CustomJimp as typeof CustomJimp & Constructor<ExtraMethodMap>;
}
|