@shibam/sticker-maker 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,130 @@
1
+ import Exif from "./utils/changeMetaInfo.js";
2
+ import MediaConverter from "./utils/convert.js";
3
+ import extractMetadata from "./utils/extractMetaInfo.js";
4
+ import * as fs from "fs";
5
+ import { Readable } from "stream";
6
+
7
+ export default class Sticker {
8
+ constructor(image, options = {}) {
9
+ this.buffer = null;
10
+ this.image = image;
11
+
12
+ this.pack = options.pack || "Default Pack";
13
+ this.author = options.author || "Unknown";
14
+ this.id = options.id || Math.random().toString(36).substring(2, 15);
15
+ this.converter = new MediaConverter({ quality: options.quality || 80 });
16
+
17
+ this.setCategories(options.category);
18
+ this.setQuality(options.quality);
19
+ this.setText(options.text);
20
+ }
21
+
22
+ async processImage(image) {
23
+ if (Buffer.isBuffer(image)) {
24
+ return image;
25
+ }
26
+
27
+ if (typeof image === "string") {
28
+ if (image.startsWith("http://") || image.startsWith("https://")) {
29
+ try {
30
+ const response = await fetch(image);
31
+ const arrayBuffer = await response.arrayBuffer();
32
+ return Buffer.from(arrayBuffer);
33
+ } catch (error) {
34
+ throw new Error("Failed to fetch image from URL: " + error.message);
35
+ }
36
+ }
37
+
38
+ try {
39
+ return await fs.promises.readFile(image);
40
+ } catch (error) {
41
+ throw new Error("Failed to read image file: " + error.message);
42
+ }
43
+ }
44
+
45
+ if (image instanceof Readable) {
46
+ return new Promise((resolve, reject) => {
47
+ const chunks = [];
48
+ image.on("data", (chunk) => chunks.push(chunk));
49
+ image.on("end", () => resolve(Buffer.concat(chunks)));
50
+ image.on("error", reject);
51
+ });
52
+ }
53
+
54
+ throw new Error(
55
+ "Invalid image input. Must be Buffer, URL, file path, or ReadableStream"
56
+ );
57
+ }
58
+
59
+ setCategories(categories) {
60
+ if (!categories) {
61
+ this.category = [];
62
+ return;
63
+ }
64
+
65
+ if (!Array.isArray(categories)) {
66
+ throw new Error("Categories must be an array of emoji strings");
67
+ }
68
+
69
+ const emojiRegex = /\p{Emoji}/u;
70
+ categories.forEach((category) => {
71
+ if (!emojiRegex.test(category)) {
72
+ throw new Error(`Invalid emoji category: ${category}`);
73
+ }
74
+ });
75
+
76
+ this.category = categories;
77
+ }
78
+
79
+ setQuality(quality) {
80
+ if (quality === undefined) {
81
+ this.quality = 100;
82
+ return;
83
+ }
84
+
85
+ if (typeof quality !== "number" || quality < 0 || quality > 100) {
86
+ throw new Error("Quality must be a number between 0 and 100");
87
+ }
88
+
89
+ this.quality = quality;
90
+ }
91
+
92
+ setText(text) {
93
+ if (text && typeof text !== "string") {
94
+ throw new Error("Text must be a string");
95
+ }
96
+
97
+ this.text = text || null;
98
+ }
99
+
100
+ async build() {
101
+ // Process input to buffer
102
+ const inputBuffer = await this.processImage(this.image);
103
+
104
+ // Convert to WebP using imported converter
105
+ const webpBuffer = await this.converter.convertToWebp(inputBuffer);
106
+
107
+ // Add metadata using imported Exif handler
108
+ const exif = new Exif({
109
+ id: this.id,
110
+ pack: this.pack,
111
+ author: this.author,
112
+ category: this.category,
113
+ });
114
+
115
+ this.buffer = await exif.add(webpBuffer);
116
+ return this.buffer;
117
+ }
118
+
119
+ async toBuffer() {
120
+ return await this.build();
121
+ }
122
+
123
+ async metadata() {
124
+ if (!this.buffer) {
125
+ await this.build();
126
+ }
127
+
128
+ return await extractMetadata(this.buffer);
129
+ }
130
+ }
package/package.json CHANGED
@@ -1,48 +1,20 @@
1
- {
2
- "name": "@shibam/sticker-maker",
3
- "version": "1.2.4",
4
- "description": "A package for creating stickers",
5
- "main": "dist/index.js",
6
- "type": "module",
7
- "files": [
8
- "dist"
9
- ],
10
- "scripts": {
11
- "build": "tsc -p .",
12
- "lint": "eslint \"src/**/*.ts\"",
13
- "prepublish": "npm run build",
14
- "fmt": "prettier --config .prettierrc \"**/*.{ts,mjs}\" --write",
15
- "test": "mocha --timeout 60000 -r ts-node/register \"tests/**/*.test.ts\"",
16
- "clean:webp": "find ./ -name '*.webp' -delete",
17
- "release": "release-it"
18
- },
19
- "author": "Shibam Dey",
20
- "license": "MIT",
21
- "repository": {
22
- "type": "git",
23
- "url": "https://github.com/ShibamDey69/Sticker-Maker.git"
24
- },
25
- "keywords": [
26
- "stickers",
27
- "sticker maker",
28
- "image processing",
29
- "wa sticker maker",
30
- "wasticker",
31
- "nodejs",
32
- "typescript"
33
- ],
34
- "dependencies": {
35
- "canvas": "^3.0.1",
36
- "file-type": "^20.0.0",
37
- "fluent-ffmpeg": "^2.1.3",
38
- "node-webpmux": "^3.2.0",
39
- "sharp": "^0.33.5"
40
- },
41
- "devDependencies": {
42
- "@types/fluent-ffmpeg": "^2.1.24",
43
- "@types/node": "^20.17.14",
44
- "@types/sharp": "^0.28.5",
45
- "tsx": "^4.7.1",
46
- "typescript": "^5.4.5"
47
- }
48
- }
1
+ {
2
+ "name": "@shibam/sticker-maker",
3
+ "version": "1.2.6",
4
+ "main": "index.js",
5
+ "type": "module",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [],
10
+ "author": "",
11
+ "license": "ISC",
12
+ "description": "",
13
+ "dependencies": {
14
+ "cwebp": "^3.1.0",
15
+ "file-type": "^20.0.0",
16
+ "jimp": "^1.6.0",
17
+ "node-webpmux": "^3.2.0",
18
+ "webp-converter": "^2.3.3"
19
+ }
20
+ }
Binary file
package/test/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import Sticker from '../index.js';
2
+ import * as fs from 'fs';
3
+ const sticker = new Sticker('./test/lol.mp4',{
4
+ pack: 'My Pack',
5
+ author: 'Me',
6
+ category: ['😹'],
7
+ quality: 80,
8
+ text: 'Hello World'
9
+ });
10
+ sticker.metadata().then(console.log);
11
+ fs.writeFileSync('sticker.webp', await sticker.build());
package/test/lol.mp4 ADDED
Binary file
@@ -0,0 +1,43 @@
1
+ import Image from "node-webpmux"
2
+ import { TextEncoder } from "util";
3
+
4
+ class Exif {
5
+ constructor(options = {}) {
6
+ this.data = {
7
+ 'sticker-pack-id': options.id || '',
8
+ 'sticker-pack-name': options.pack || '',
9
+ 'sticker-pack-publisher': options.author || '',
10
+ 'emojis': options.category || ['😹']
11
+ };
12
+ this.exif = null;
13
+ }
14
+
15
+ build() {
16
+ const data = JSON.stringify(this.data);
17
+ const exif = Buffer.concat([
18
+ Buffer.from([
19
+ 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00,
20
+ 0x00, 0x16, 0x00, 0x00, 0x00
21
+ ]),
22
+ Buffer.from(data, 'utf-8')
23
+ ]);
24
+ exif.writeUIntLE(new TextEncoder().encode(data).length, 14, 4);
25
+ return exif;
26
+ }
27
+
28
+ async add(image) {
29
+ const exif = this.exif || this.build();
30
+
31
+ if (image instanceof Image.Image) {
32
+ image.exif = exif;
33
+ return await image.save(null);
34
+ }
35
+
36
+ const img = new Image.Image();
37
+ await img.load(image);
38
+ img.exif = exif;
39
+ return await img.save(null);
40
+ }
41
+ }
42
+
43
+ export default Exif;
@@ -0,0 +1,105 @@
1
+ import { exec as execCallback } from "child_process";
2
+ import { promisify } from "util";
3
+ import { promises as fs } from "fs";
4
+ import { tmpdir } from "os";
5
+ import { join } from "path";
6
+ import { fileTypeFromBuffer } from "file-type";
7
+
8
+
9
+ const exec = promisify(execCallback);
10
+
11
+ export default class MediaConverter {
12
+ constructor(options = {}) {
13
+ this.fps = options.fps || 12;
14
+ this.quality = options.quality || 80;
15
+ this.width = options.width || 512;
16
+ this.mime = null;
17
+ }
18
+
19
+ async convertToWebp(buffer) {
20
+ const fileType = await fileTypeFromBuffer(buffer);
21
+ if (!fileType) throw new Error("Invalid file type");
22
+
23
+ this.mime = fileType.mime;
24
+
25
+ if (this.mime.startsWith("video/")) {
26
+ const gif = await this.videoToGif(buffer);
27
+ return await this.gifToWebp(gif);
28
+ } else if (this.mime === "image/gif") {
29
+ return await this.gifToWebp(buffer);
30
+ } else if (this.mime.startsWith("image/")) {
31
+ return await this.imageToWebp(buffer);
32
+ }
33
+
34
+ throw new Error(`Unsupported file type: ${this.mime}`);
35
+ }
36
+
37
+ async videoToGif(buffer) {
38
+ const tempInput = join(tmpdir(), `input_${Date.now()}.mp4`);
39
+ const tempOutput = join(tmpdir(), `output_${Date.now()}.gif`);
40
+
41
+ try {
42
+ await fs.writeFile(tempInput, buffer);
43
+
44
+ const ffmpegCmd = `ffmpeg -i "${tempInput}" -vf "fps=${this.fps},scale=${this.width}:-1:flags=lanczos" -loop 0 -lossless 0 -t 7 -preset ultrafast -f gif "${tempOutput}"`;
45
+ await exec(ffmpegCmd);
46
+
47
+ const gifBuffer = await fs.readFile(tempOutput);
48
+
49
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
50
+
51
+ return gifBuffer;
52
+ } catch (error) {
53
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
54
+ throw new Error(`Failed to convert video to gif: ${error.message}`);
55
+ }
56
+ }
57
+
58
+ async gifToWebp(buffer) {
59
+ const tempInput = join(tmpdir(), `input_${Date.now()}.gif`);
60
+ const tempOutput = join(tmpdir(), `output_${Date.now()}.webp`);
61
+
62
+ try {
63
+ await fs.writeFile(tempInput, buffer);
64
+
65
+ // Use gif2webp to convert GIF to WebP
66
+ const gif2webpCmd = `gif2webp "${tempInput}" -q ${this.quality} -o "${tempOutput}"`;
67
+ await exec(gif2webpCmd);
68
+
69
+ const webpBuffer = await fs.readFile(tempOutput);
70
+
71
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
72
+
73
+ return webpBuffer;
74
+ } catch (error) {
75
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
76
+ throw new Error(`Failed to convert gif to webp: ${error.message}`);
77
+ }
78
+ }
79
+
80
+ async imageToWebp(buffer) {
81
+ const tempInput = join(tmpdir(), `input_${Date.now()}.png`);
82
+ const tempOutput = join(tmpdir(), `output_${Date.now()}.webp`);
83
+
84
+ try {
85
+ // Write the input buffer to a temporary file
86
+ await fs.writeFile(tempInput, buffer);
87
+
88
+ // Use cwebp to convert the image to WebP
89
+ const cwebpCmd = `cwebp "${tempInput}" -q ${this.quality} -o "${tempOutput}"`;
90
+ await exec(cwebpCmd);
91
+
92
+ // Read the resulting WebP file as a buffer
93
+ const webpBuffer = await fs.readFile(tempOutput);
94
+
95
+ // Clean up temporary files
96
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
97
+
98
+ return webpBuffer; // Return the WebP buffer as output
99
+ } catch (error) {
100
+ // Clean up temporary files in case of error
101
+ await Promise.all([fs.unlink(tempInput).catch(() => {}), fs.unlink(tempOutput).catch(() => {})]);
102
+ throw new Error(`Failed to convert image to webp: ${error.message}`);
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,10 @@
1
+ import Image from 'node-webpmux'
2
+
3
+ const extractMetadata = async (image) => {
4
+ const img = new Image.Image()
5
+ await img.load(image)
6
+ const exif = img.exif?.toString('utf-8') ?? '{}'
7
+ return JSON.parse(exif.substring(exif.indexOf('{'), exif.lastIndexOf('}') + 1) ?? '{}')
8
+ }
9
+
10
+ export default extractMetadata
package/dist/index.js DELETED
@@ -1,119 +0,0 @@
1
- import * as fs from 'fs';
2
- import Utils from './lib/utils.js';
3
- import convert from './lib/ToWebp.js';
4
- import { StickerTypes } from './types/StickerTypes.js';
5
- import MetaInfoChanger from './lib/changeMetaInfo.js';
6
- import extractMetaData from './lib/extractMetaData.js';
7
- class Sticker {
8
- data;
9
- metaInfo;
10
- buffer;
11
- mimeType;
12
- extType;
13
- utils = new Utils();
14
- outBuffer;
15
- activeBuff;
16
- activeMeta;
17
- constructor(data, metaInfo = {}) {
18
- this.data = data;
19
- this.metaInfo = metaInfo;
20
- this.buffer = Buffer.from([]);
21
- this.outBuffer = Buffer.from([]);
22
- this.activeBuff = false;
23
- this.activeMeta = false;
24
- this.mimeType = '';
25
- this.extType = '';
26
- }
27
- /**
28
- * Initializes the Sticker instance.
29
- * - Sets default values for metaInfo.
30
- * - Reads and analyzes input data to determine MIME type and extension type.
31
- * - Generates ID and quality metadata if not provided.
32
- */
33
- async initialize() {
34
- try {
35
- this.buffer = await this.utils.buffer(this.data);
36
- const fileType = await this.utils.getMimeType(this.buffer);
37
- this.mimeType = fileType?.mime ?? '';
38
- this.extType = fileType?.ext ?? '';
39
- this.metaInfo.pack = this.metaInfo.pack ?? '';
40
- this.metaInfo.author = this.metaInfo.author ?? '';
41
- this.metaInfo.id = this.metaInfo.id ?? this.utils.getId();
42
- this.metaInfo.category = this.metaInfo.category ?? [];
43
- this.metaInfo.type = this.metaInfo.type ?? StickerTypes.DEFAULT;
44
- this.metaInfo.quality = this.metaInfo?.quality ?? this.utils.getQuality(this.buffer);
45
- this.metaInfo.text = this.metaInfo.text ?? '';
46
- }
47
- catch (error) {
48
- throw new Error(`Initialization error: ${error}`);
49
- }
50
- }
51
- /**
52
- * Converts input data to a Buffer containing the converted content.
53
- * @returns Promise<Buffer> A Promise resolving to the converted content as Buffer.
54
- */
55
- async toBuffer() {
56
- try {
57
- await this.initialize();
58
- const buffer = await convert(this.buffer, this.metaInfo, this.extType, this.mimeType);
59
- this.outBuffer = await new MetaInfoChanger(this.metaInfo).add(buffer);
60
- this.activeBuff = true;
61
- return this.outBuffer;
62
- }
63
- catch (error) {
64
- this.activeBuff = false;
65
- throw new Error(`Conversion to buffer failed: ${error}`);
66
- }
67
- }
68
- /**
69
- * Converts input data and writes it to a file at the specified outputPath.
70
- * @param outputPath The path where the converted file will be saved.
71
- * @returns Promise<void> A Promise resolving when the file is successfully written.
72
- */
73
- async toFile(outputPath) {
74
- try {
75
- if (!this.activeBuff && !this.activeMeta && this.extType?.includes('webp')) {
76
- await this.changeMetaInfo();
77
- }
78
- else {
79
- await this.toBuffer();
80
- }
81
- await fs.promises.writeFile(outputPath, this.outBuffer);
82
- }
83
- catch (error) {
84
- throw new Error(`Conversion to file failed: ${error}`);
85
- }
86
- }
87
- /**
88
- * Changes the metadata of the sticker.
89
- * @param newMetaInfo Partial metadata to update.
90
- * @returns Promise<Buffer> A Promise resolving to the Buffer with updated metadata.
91
- */
92
- async changeMetaInfo() {
93
- try {
94
- await this.initialize();
95
- this.outBuffer = await new MetaInfoChanger(this.metaInfo).add(this.buffer);
96
- this.activeMeta = true;
97
- return this.outBuffer;
98
- }
99
- catch (error) {
100
- this.activeMeta = false;
101
- throw new Error(`Error changing meta info: ${error}`);
102
- }
103
- }
104
- /**
105
- * Extracts metadata from the provided data.
106
- * @param data Buffer containing the data to extract metadata from.
107
- * @returns Promise<Partial<MetaDataType>> A Promise resolving to the extracted metadata.
108
- */
109
- async extractMetaData(data) {
110
- try {
111
- await this.initialize();
112
- return extractMetaData(data);
113
- }
114
- catch (error) {
115
- throw new Error(`Error extracting meta data: ${error}`);
116
- }
117
- }
118
- }
119
- export { Sticker, StickerTypes };
@@ -1,61 +0,0 @@
1
- import sharp from 'sharp';
2
- import { StickerTypes } from '../types/StickerTypes.js';
3
- import toGif from './toGif.js';
4
- import TextOnImg from './textOnImg.js';
5
- const textOnImg = new TextOnImg();
6
- /**
7
- * Converts a given buffer to WebP format with optional transformations.
8
- *
9
- * @param {Buffer} buffer - The input buffer to be converted.
10
- * @param {Partial<MetaDataType>} metaInfo - Metadata information for the conversion.
11
- * @param {string} mimeExt - The MIME extension of the input buffer.
12
- * @param {string} mimeType - The MIME type of the input buffer.
13
- * @returns {Promise<Buffer>} - A promise that resolves to the converted WebP buffer.
14
- */
15
- const ToWebp = async (buffer, metaInfo, mimeExt, mimeType) => {
16
- try {
17
- if (mimeExt === 'webp')
18
- return buffer;
19
- let data = (mimeType?.includes('video')
20
- ? await toGif(buffer, mimeExt, metaInfo.type || StickerTypes.DEFAULT, metaInfo.text ?? '')
21
- : metaInfo.text
22
- ? await textOnImg.drawText(buffer, metaInfo.text)
23
- : buffer);
24
- let isAnimated = mimeType?.includes('video') || mimeExt?.includes('gif');
25
- const res = sharp(data, { animated: isAnimated });
26
- if (metaInfo.type === StickerTypes.CIRCLE) {
27
- res.resize(512, 512, {
28
- fit: sharp.fit.cover
29
- }).composite([
30
- {
31
- input: Buffer.from(`<svg width="512" height="512"><circle cx="256" cy="256" r="256" fill=""/></svg>`),
32
- blend: 'dest-in',
33
- gravity: 'northeast',
34
- tile: true
35
- }
36
- ]);
37
- }
38
- else if (metaInfo.type === StickerTypes.SQUARE && !mimeType?.includes('video')) {
39
- res.resize(512, 512, {
40
- fit: sharp.fit.fill
41
- });
42
- }
43
- else {
44
- res.resize(512, 512, {
45
- fit: sharp.fit.contain,
46
- background: { r: 0, g: 0, b: 0, alpha: 0 }
47
- });
48
- }
49
- return res
50
- .toFormat('webp')
51
- .webp({
52
- quality: metaInfo.quality,
53
- lossless: mimeExt.includes('gif') ? true : false
54
- })
55
- .toBuffer();
56
- }
57
- catch (error) {
58
- throw new Error(`Conversion failed: ${error}`);
59
- }
60
- };
61
- export default ToWebp;
@@ -1,56 +0,0 @@
1
- import Image from 'node-webpmux';
2
- import { TextEncoder } from 'util';
3
- /**
4
- * The Exif class is responsible for handling the metadata (Exif data)
5
- * for sticker images, particularly those used in messaging applications.
6
- */
7
- export default class Exif {
8
- data = {};
9
- exif = null;
10
- /**
11
- * Constructs an Exif instance with the given options.
12
- * @param options - An object containing metadata for the sticker.
13
- */
14
- constructor(options) {
15
- this.data['sticker-pack-id'] = options.id || '';
16
- this.data['sticker-pack-name'] = options.pack || '';
17
- this.data['sticker-pack-publisher'] = options.author || '';
18
- this.data['emojis'] = options.category || ['😹'];
19
- }
20
- /**
21
- * Builds the Exif metadata as a Buffer.
22
- * @returns A Buffer containing the constructed Exif data.
23
- */
24
- build = () => {
25
- const data = JSON.stringify(this.data);
26
- const exif = Buffer.concat([
27
- Buffer.from([
28
- 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00,
29
- 0x00, 0x16, 0x00, 0x00, 0x00
30
- ]),
31
- Buffer.from(data, 'utf-8')
32
- ]);
33
- exif.writeUIntLE(new TextEncoder().encode(data).length, 14, 4);
34
- return exif;
35
- };
36
- /**
37
- * Adds the Exif metadata to the given image.
38
- * @param image - A Buffer or Image instance representing the image to which Exif data should be added.
39
- * @returns A Promise that resolves to a Buffer containing the image with the added Exif data.
40
- */
41
- add = async (image) => {
42
- const exif = this.exif || this.build();
43
- // Load the image if it is not already an instance of Image.Image.
44
- image =
45
- image instanceof Image.Image
46
- ? image
47
- : await (async () => {
48
- const img = new Image.Image();
49
- await img.load(image);
50
- return img;
51
- })();
52
- // Set the Exif data on the image and save it.
53
- image.exif = exif;
54
- return await image.save(null);
55
- };
56
- }
@@ -1,12 +0,0 @@
1
- import Image from 'node-webpmux';
2
- /**
3
- * Extracts metadata from a WebP image.
4
- * @param {Buffer}image - The image buffer to extract metadata from
5
- */
6
- const extractMetadata = async (image) => {
7
- const img = new Image.Image();
8
- await img.load(image);
9
- const exif = img.exif?.toString('utf-8') ?? '{}';
10
- return JSON.parse(exif.substring(exif.indexOf('{'), exif.lastIndexOf('}') + 1) ?? '{}');
11
- };
12
- export default extractMetadata;
@@ -1,13 +0,0 @@
1
- import * as fs from "fs/promises";
2
- const textOnGif = async (fileName, text) => {
3
- return new Promise(async (resolve, reject) => {
4
- try {
5
- let buff = await fs.readFile(fileName);
6
- resolve(buff);
7
- }
8
- catch (error) {
9
- reject(error);
10
- }
11
- });
12
- };
13
- export default textOnGif;
@@ -1,62 +0,0 @@
1
- import { createCanvas, loadImage } from 'canvas';
2
- export default class TextOnImage {
3
- fontSize;
4
- maxCharsPerLine;
5
- constructor(maxCharsPerLine = 25) {
6
- this.fontSize = 175;
7
- this.maxCharsPerLine = maxCharsPerLine;
8
- }
9
- wrapText(ctx, text) {
10
- const words = text.split(' ');
11
- let lines = [];
12
- let currentLine = words[0];
13
- for (let i = 1; i < words.length; i++) {
14
- const word = words[i];
15
- const testLine = `${currentLine} ${word}`;
16
- const { width: testWidth } = ctx.measureText(testLine);
17
- if (testWidth > ctx.canvas.width * 0.9) {
18
- lines.push(currentLine);
19
- currentLine = word;
20
- }
21
- else {
22
- currentLine = testLine;
23
- }
24
- }
25
- lines.push(currentLine);
26
- return lines;
27
- }
28
- async drawText(imageBuffer, text, padding = { x: 10, y: 10 }) {
29
- const image = await loadImage(imageBuffer);
30
- const canvas = createCanvas(image.width, image.height);
31
- const ctx = canvas.getContext('2d');
32
- // Draw the image on canvas
33
- ctx.drawImage(image, 0, 0);
34
- // Calculate font size based on image height
35
- this.fontSize = Math.floor(image.height / 10);
36
- ctx.font = `bold ${this.fontSize}px Arial`;
37
- ctx.fillStyle = 'white';
38
- ctx.textAlign = 'center';
39
- ctx.textBaseline = 'top';
40
- ctx.lineWidth = 4;
41
- ctx.strokeStyle = 'black';
42
- // Wrap the text to fit within the canvas width
43
- const lines = this.wrapText(ctx, text);
44
- const lineHeight = this.fontSize * 1.2;
45
- const totalTextHeight = lines.length * lineHeight;
46
- // If text height exceeds image height, adjust font size
47
- if (totalTextHeight + 2 * padding.y > canvas.height) {
48
- this.fontSize = Math.floor((canvas.height - 2 * padding.y) / (lines.length * 1.2));
49
- ctx.font = `bold ${this.fontSize}px Arial`;
50
- }
51
- // Start text positioning at the bottom, above padding
52
- let y = canvas.height - totalTextHeight - padding.y;
53
- // Draw each line of text with stroke and fill for better contrast
54
- lines.forEach((line) => {
55
- const x = canvas.width / 2;
56
- ctx.strokeText(line, x, y);
57
- ctx.fillText(line, x, y);
58
- y += lineHeight;
59
- });
60
- return canvas.toBuffer('image/png');
61
- }
62
- }
package/dist/lib/toGif.js DELETED
@@ -1,55 +0,0 @@
1
- import ffmpeg from 'fluent-ffmpeg';
2
- import { tmpdir } from 'os';
3
- import { writeFile, readFile, unlink } from 'fs/promises';
4
- import { join } from 'path';
5
- import { StickerTypes } from '../types/StickerTypes.js';
6
- import TextOnGif from './textOnGif.js';
7
- const videoToGif = (buffer, extType, type, text = '') => {
8
- return new Promise(async (resolve, reject) => {
9
- const execute = async (attempt) => {
10
- const filename = join(tmpdir(), `${Math.random().toString(36)}.${extType}`);
11
- const outputFilename = join(tmpdir(), `${Math.random().toString(36)}.gif`);
12
- const retries = 3;
13
- try {
14
- await writeFile(filename, buffer);
15
- const shape = type === StickerTypes.SQUARE
16
- ? 'scale=320:-1:flags=lanczos,fps=10,crop=min(iw\\,ih):min(iw\\,ih)'
17
- : 'scale=320:-1:flags=lanczos,fps=20';
18
- await new Promise((resolveFfmpeg, rejectFfmpeg) => {
19
- ffmpeg(filename)
20
- .inputFormat(extType)
21
- .outputOptions([
22
- '-vf',
23
- shape,
24
- '-loop',
25
- '0',
26
- '-lossless',
27
- '0',
28
- '-t',
29
- '7',
30
- '-preset',
31
- 'ultrafast'
32
- ])
33
- .toFormat('gif')
34
- .save(outputFilename)
35
- .on('end', resolveFfmpeg)
36
- .on('error', rejectFfmpeg);
37
- });
38
- const gifBuffer = text ? await TextOnGif(outputFilename, text) : await readFile(outputFilename);
39
- await Promise.all([unlink(filename), unlink(outputFilename)]);
40
- resolve(gifBuffer);
41
- }
42
- catch (error) {
43
- if (attempt < retries) {
44
- execute(++attempt);
45
- }
46
- else {
47
- await Promise.all([unlink(filename).catch(() => { }), unlink(outputFilename).catch(() => { })]);
48
- reject(error);
49
- }
50
- }
51
- };
52
- execute(1);
53
- });
54
- };
55
- export default videoToGif;
package/dist/lib/utils.js DELETED
@@ -1,82 +0,0 @@
1
- import { Readable } from 'stream';
2
- import * as fs from 'fs';
3
- export default class Utils {
4
- constructor() { }
5
- /**
6
- * Converts various types of input data to a Buffer.
7
- * @param data Input data as Buffer, string (file path), or Readable stream.
8
- * @returns Promise<Buffer> A Promise resolving to the converted Buffer.
9
- * @throws Error if conversion fails.
10
- */
11
- async buffer(data) {
12
- try {
13
- const buffer = typeof data === 'string'
14
- ? await fs.promises.readFile(data)
15
- : data instanceof Readable
16
- ? await this.streamToBuffer(data)
17
- : Buffer.from(data);
18
- return buffer;
19
- }
20
- catch (error) {
21
- throw new Error(`Error converting to buffer: ${error}`);
22
- }
23
- }
24
- /**
25
- * Converts a Readable stream to a Buffer.
26
- * @param stream Readable stream to convert.
27
- * @returns Promise<Buffer> A Promise resolving to the converted Buffer.
28
- */
29
- async streamToBuffer(stream) {
30
- const chunks = [];
31
- return new Promise((resolve, reject) => {
32
- stream.on('data', (chunk) => {
33
- if (Buffer.isBuffer(chunk)) {
34
- chunks.push(chunk);
35
- }
36
- else {
37
- chunks.push(Buffer.from(chunk));
38
- }
39
- });
40
- stream.on('end', () => {
41
- resolve(Buffer.concat(chunks));
42
- });
43
- stream.on('error', (err) => {
44
- reject(err);
45
- });
46
- });
47
- }
48
- /**
49
- * Determines the quality of the data based on its size.
50
- * @param data Buffer containing the data.
51
- * @returns number Quality value based on data size.
52
- */
53
- getQuality(data) {
54
- let buffer = Buffer.from(data);
55
- let bytes = buffer.length / 1024;
56
- let quality = bytes > 4 * 1024 ? 8 : bytes > 3 * 1024 ? 10 : bytes > 2 * 1024 ? 12 : 15;
57
- return quality;
58
- }
59
- /**
60
- * Determines the MIME type of the data buffer.
61
- * @param data Buffer containing the data.
62
- * @returns Promise<{ mime: string; ext: string }> A Promise resolving to an object with MIME type and extension.
63
- */
64
- async getMimeType(data) {
65
- try {
66
- const { fileTypeFromBuffer } = await import('file-type');
67
- const fileType = await fileTypeFromBuffer(data);
68
- return fileType;
69
- }
70
- catch (error) {
71
- console.error(`Error getting MIME type: ${error}`);
72
- return undefined;
73
- }
74
- }
75
- /**
76
- * Generates a random ID.
77
- * @returns string A random alphanumeric ID.
78
- */
79
- getId() {
80
- return [...Array(5)].map(() => Math.random().toString(36).substring(2, 15)).join('');
81
- }
82
- }
@@ -1,6 +0,0 @@
1
- export var StickerTypes;
2
- (function (StickerTypes) {
3
- StickerTypes[StickerTypes["DEFAULT"] = 0] = "DEFAULT";
4
- StickerTypes[StickerTypes["SQUARE"] = 1] = "SQUARE";
5
- StickerTypes[StickerTypes["CIRCLE"] = 2] = "CIRCLE";
6
- })(StickerTypes || (StickerTypes = {}));
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
package/readme.md DELETED
@@ -1,112 +0,0 @@
1
- # @shibam/sticker-maker
2
-
3
- `@shibam/sticker-maker` is a lightweight utility library designed for converting images and videos into stickers while allowing customization of metadata. you have to download ffmpeg and canvas dependencies globally. It supports various input types and ensures high-quality sticker conversion. This module has minimal dependencies, ensuring efficient performance. If you encounter any issues, please feel free to open an issue. However, please check if a similar issue has already been reported before creating a new one. Happy Coding (⁠≧⁠▽⁠≦⁠).
4
-
5
- # Sticker Class
6
-
7
- The `Sticker` class is a utility for converting images and videos into sticker format, with options for metadata customization and manipulation.
8
-
9
- ## Installation
10
-
11
- You can install the package using npm:
12
-
13
- ```sh
14
- npm install @shibam/sticker-maker
15
- ```
16
- ## Usage
17
-
18
- Here's how you can use the `Sticker` class:
19
-
20
- ```typescript
21
- import fs from "fs";
22
- import { Readable } from "stream";
23
- import { Sticker, StickerTypes } from "@shibam/sticker-maker";
24
-
25
- // Example 1: Create a new sticker instance and convert to buffer
26
- const sticker = new Sticker("path/to/image.png", {
27
- pack: "My Sticker Pack",
28
- author: "Shibam",
29
- id: "123467890",
30
- category: ['😂','😹'],
31
- type: StickerTypes.DEFAULT,
32
- quality: 30,
33
- text:"hello baka!" // if you want to use this download canvas dependecies
34
- });
35
-
36
- try {
37
- const buffer = await sticker.toBuffer();
38
- console.log("Sticker converted to buffer:", buffer);
39
- } catch (error) {
40
- console.error("Error converting sticker to buffer:", error);
41
- }
42
-
43
- // Example 2: Create a new sticker instance and convert to file
44
- const sticker2 = new Sticker("path/to/another/image.png", {
45
- pack: "Another Sticker Pack",
46
- author: "John Doe",
47
- id: "987654321",
48
- category: ['😊','👍'],
49
- type: StickerTypes.CIRCLE,
50
- quality: 50,
51
- text:"hello baka!" // if you want to use this download canvas dependecies
52
- });
53
-
54
- try {
55
- await sticker2.toFile("path/to/output.webp");
56
- console.log("Sticker converted and saved to file successfully.");
57
- } catch (error) {
58
- console.error("Error converting sticker to file:", error);
59
- }
60
- ```
61
-
62
- ## Class: `Sticker`
63
-
64
- ### Constructor
65
-
66
- ```typescript
67
- new Sticker(data: Buffer | string | Readable, metaInfo?: Partial<MetaDataType>)
68
- ```
69
-
70
- - `data`: Input data for the sticker. Can be a Buffer, file path as a string, or Readable stream.
71
- - `metaInfo` (optional): Metadata about the sticker.
72
-
73
- ### Methods
74
-
75
- #### `toBuffer(): Promise<Buffer>`
76
-
77
- Converts input data to a Buffer containing the converted sticker content.
78
-
79
- #### `toFile(outputPath: string): Promise<void>`
80
-
81
- Converts input data and writes the converted sticker to a file at `outputPath`.
82
-
83
-
84
- #### `extractMetaData(data: Buffer): Promise<any>`
85
-
86
- Extracts metadata from `data` and returns the extracted information.
87
-
88
- ## Types
89
-
90
- ### `StickerTypes`
91
-
92
- An enum specifying different types of stickers:
93
-
94
- ```typescript
95
- enum StickerTypes {
96
- DEFAULT,
97
- CIRCLE,
98
- SQUARE,
99
- }
100
- ```
101
-
102
- ## License
103
-
104
- This package is licensed under the MIT License.
105
-
106
- ## Contributing
107
-
108
- Contributions are welcome. Feel free to open issues or submit pull requests on [GitHub](https://github.com/NekoSenpai69/Sticker-Maker).
109
-
110
- ---
111
-
112
- This README provides an overview of the `Sticker` class functionalities, installation instructions, examples of usage, information about types used, and guidelines for contributing to the project. Adjust paths and additional details based on your actual implementation and repository setup.