@shibam/sticker-maker 1.2.13 → 1.2.15
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/dist/index.js +156 -0
- package/dist/lib/ToWebp.js +76 -0
- package/dist/lib/changeMetaInfo.js +56 -0
- package/dist/lib/extractMetaData.js +12 -0
- package/dist/lib/textOnGif.js +24 -0
- package/dist/lib/textOnImg.js +62 -0
- package/dist/lib/toGif.js +63 -0
- package/dist/lib/utils.js +82 -0
- package/dist/types/StickerTypes.js +6 -0
- package/dist/types/categoryType.js +1 -0
- package/dist/types/metaInfoType.js +1 -0
- package/package.json +41 -9
- package/readme.md +112 -0
- package/index.js +0 -127
- package/utils/changeMetaInfo.js +0 -43
- package/utils/convert.js +0 -87
- package/utils/extractMetaInfo.js +0 -10
package/dist/index.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
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
|
+
/**
|
|
8
|
+
* Sticker class for handling sticker creation, conversion, and metadata management
|
|
9
|
+
*/
|
|
10
|
+
class Sticker {
|
|
11
|
+
utils;
|
|
12
|
+
buffer;
|
|
13
|
+
outBuffer;
|
|
14
|
+
mimeType;
|
|
15
|
+
extType;
|
|
16
|
+
isBufferProcessed;
|
|
17
|
+
isMetaProcessed;
|
|
18
|
+
data;
|
|
19
|
+
metaInfo;
|
|
20
|
+
/**
|
|
21
|
+
* Creates a new Sticker instance
|
|
22
|
+
* @param data The input data (Buffer, string path, or Readable stream)
|
|
23
|
+
* @param metaInfo Optional metadata and configuration
|
|
24
|
+
*/
|
|
25
|
+
constructor(data, metaInfo = {}) {
|
|
26
|
+
this.utils = new Utils();
|
|
27
|
+
this.buffer = Buffer.from([]);
|
|
28
|
+
this.outBuffer = Buffer.from([]);
|
|
29
|
+
this.mimeType = '';
|
|
30
|
+
this.extType = '';
|
|
31
|
+
this.isBufferProcessed = false;
|
|
32
|
+
this.isMetaProcessed = false;
|
|
33
|
+
this.data = data;
|
|
34
|
+
this.metaInfo = this.initializeMetaInfo(metaInfo);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Initialize default metadata values
|
|
38
|
+
*/
|
|
39
|
+
initializeMetaInfo(metaInfo) {
|
|
40
|
+
return {
|
|
41
|
+
pack: '',
|
|
42
|
+
author: '',
|
|
43
|
+
type: StickerTypes.DEFAULT,
|
|
44
|
+
quality: 100,
|
|
45
|
+
background: '#FFFFFF00',
|
|
46
|
+
text: '',
|
|
47
|
+
...metaInfo,
|
|
48
|
+
// Ensure categories is always an array
|
|
49
|
+
categories: metaInfo.categories || []
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Initialize the Sticker instance with file data and metadata
|
|
54
|
+
*/
|
|
55
|
+
async initialize() {
|
|
56
|
+
try {
|
|
57
|
+
// Convert input to buffer
|
|
58
|
+
this.buffer = await this.utils.buffer(this.data);
|
|
59
|
+
// Get file type information
|
|
60
|
+
const fileType = await this.utils.getMimeType(this.buffer);
|
|
61
|
+
if (!fileType) {
|
|
62
|
+
throw new Error('Unable to determine file type');
|
|
63
|
+
}
|
|
64
|
+
this.mimeType = fileType.mime;
|
|
65
|
+
this.extType = fileType.ext;
|
|
66
|
+
// Set dynamic metadata values if not provided
|
|
67
|
+
this.metaInfo = {
|
|
68
|
+
...this.metaInfo,
|
|
69
|
+
id: this.metaInfo.id ?? this.utils.getId(),
|
|
70
|
+
quality: this.metaInfo.quality ?? this.utils.getQuality(this.buffer)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
throw new Error(`Initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Convert input data to WebP buffer with metadata
|
|
79
|
+
*/
|
|
80
|
+
async toBuffer() {
|
|
81
|
+
try {
|
|
82
|
+
await this.initialize();
|
|
83
|
+
// Convert to WebP
|
|
84
|
+
const convertedBuffer = await convert({
|
|
85
|
+
buffer: this.buffer,
|
|
86
|
+
metaInfo: {
|
|
87
|
+
...this.metaInfo,
|
|
88
|
+
categories: this.metaInfo.categories // Map categories to category for compatibility
|
|
89
|
+
},
|
|
90
|
+
mimeExt: this.extType,
|
|
91
|
+
mimeType: this.mimeType
|
|
92
|
+
});
|
|
93
|
+
// Add metadata
|
|
94
|
+
this.outBuffer = await new MetaInfoChanger({
|
|
95
|
+
...this.metaInfo,
|
|
96
|
+
categories: this.metaInfo.categories
|
|
97
|
+
}).add(convertedBuffer);
|
|
98
|
+
this.isBufferProcessed = true;
|
|
99
|
+
return this.outBuffer;
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
this.isBufferProcessed = false;
|
|
103
|
+
throw new Error(`Buffer conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Save the sticker to a file
|
|
108
|
+
*/
|
|
109
|
+
async toFile(outputPath) {
|
|
110
|
+
try {
|
|
111
|
+
// Process buffer if needed
|
|
112
|
+
if (!this.isBufferProcessed && !this.isMetaProcessed && this.extType?.includes('webp')) {
|
|
113
|
+
await this.changeMetaInfo();
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
await this.toBuffer();
|
|
117
|
+
}
|
|
118
|
+
// Write to file
|
|
119
|
+
await fs.writeFile(outputPath, this.outBuffer);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
throw new Error(`File conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Update sticker metadata
|
|
127
|
+
*/
|
|
128
|
+
async changeMetaInfo() {
|
|
129
|
+
try {
|
|
130
|
+
await this.initialize();
|
|
131
|
+
this.outBuffer = await new MetaInfoChanger({
|
|
132
|
+
...this.metaInfo,
|
|
133
|
+
categories: this.metaInfo.categories
|
|
134
|
+
}).add(this.buffer);
|
|
135
|
+
this.isMetaProcessed = true;
|
|
136
|
+
return this.outBuffer;
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
this.isMetaProcessed = false;
|
|
140
|
+
throw new Error(`Metadata update failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Extract metadata from a buffer
|
|
145
|
+
*/
|
|
146
|
+
async extractMetaData(data) {
|
|
147
|
+
try {
|
|
148
|
+
await this.initialize();
|
|
149
|
+
return extractMetaData(data);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
throw new Error(`Metadata extraction failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export { Sticker, StickerTypes };
|
|
@@ -0,0 +1,76 @@
|
|
|
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
|
+
/**
|
|
6
|
+
* Converts media (image/video) to WebP format with optional transformations
|
|
7
|
+
* @param options Configuration options for the conversion
|
|
8
|
+
* @returns Promise<Buffer> The resulting WebP buffer
|
|
9
|
+
*/
|
|
10
|
+
const ToWebp = async ({ buffer, metaInfo, mimeExt, mimeType }) => {
|
|
11
|
+
try {
|
|
12
|
+
// Return early if already in WebP format
|
|
13
|
+
if (mimeExt === 'webp') {
|
|
14
|
+
return buffer;
|
|
15
|
+
}
|
|
16
|
+
const textOnImg = new TextOnImg();
|
|
17
|
+
// Process initial buffer based on type and text requirements
|
|
18
|
+
const processedBuffer = await (async () => {
|
|
19
|
+
if (mimeType?.includes('video')) {
|
|
20
|
+
return toGif({
|
|
21
|
+
buffer,
|
|
22
|
+
extType: mimeExt,
|
|
23
|
+
type: metaInfo.type || StickerTypes.DEFAULT,
|
|
24
|
+
text: metaInfo.text ?? ''
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
if (metaInfo.text) {
|
|
28
|
+
return textOnImg.drawText(buffer, metaInfo.text);
|
|
29
|
+
}
|
|
30
|
+
return buffer;
|
|
31
|
+
})();
|
|
32
|
+
// Determine if content is animated
|
|
33
|
+
const isAnimated = mimeType?.includes('video') || mimeExt?.includes('gif');
|
|
34
|
+
// Initialize sharp with processed buffer
|
|
35
|
+
const sharpInstance = sharp(processedBuffer, { animated: isAnimated });
|
|
36
|
+
// Apply transformations based on sticker type
|
|
37
|
+
switch (metaInfo.type) {
|
|
38
|
+
case StickerTypes.CIRCLE: {
|
|
39
|
+
const circleSvg = Buffer.from('<svg width="512" height="512"><circle cx="256" cy="256" r="256" fill=""/></svg>');
|
|
40
|
+
await sharpInstance
|
|
41
|
+
.resize(512, 512, { fit: sharp.fit.cover })
|
|
42
|
+
.composite([{
|
|
43
|
+
input: circleSvg,
|
|
44
|
+
blend: 'dest-in',
|
|
45
|
+
gravity: 'northeast',
|
|
46
|
+
tile: true
|
|
47
|
+
}]);
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
case StickerTypes.SQUARE: {
|
|
51
|
+
if (!mimeType?.includes('video')) {
|
|
52
|
+
await sharpInstance.resize(512, 512, { fit: sharp.fit.fill });
|
|
53
|
+
}
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
default: {
|
|
57
|
+
await sharpInstance.resize(512, 512, {
|
|
58
|
+
fit: sharp.fit.contain,
|
|
59
|
+
background: { r: 0, g: 0, b: 0, alpha: 0 }
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Convert to WebP format with appropriate options
|
|
64
|
+
return sharpInstance
|
|
65
|
+
.toFormat('webp')
|
|
66
|
+
.webp({
|
|
67
|
+
quality: metaInfo.quality,
|
|
68
|
+
lossless: mimeExt.includes('gif')
|
|
69
|
+
})
|
|
70
|
+
.toBuffer();
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
throw new Error(`WebP conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
export default ToWebp;
|
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
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;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import TextOnGif from 'text-on-gif';
|
|
2
|
+
const textOnGif = async (fileName, text) => {
|
|
3
|
+
return new Promise(async (resolve, reject) => {
|
|
4
|
+
try {
|
|
5
|
+
const gif = new TextOnGif({
|
|
6
|
+
file_path: fileName,
|
|
7
|
+
font_size: '32px',
|
|
8
|
+
font_color: 'white',
|
|
9
|
+
font_family: 'Arial',
|
|
10
|
+
stroke_color: 'black',
|
|
11
|
+
stroke_width: 3
|
|
12
|
+
});
|
|
13
|
+
const buff = await gif.textOnGif({
|
|
14
|
+
text,
|
|
15
|
+
get_as_buffer: true
|
|
16
|
+
});
|
|
17
|
+
resolve(buff);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
reject(error);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
export default textOnGif;
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import ffmpeg from 'fluent-ffmpeg';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import fs from 'fs-extra';
|
|
4
|
+
import { join } from 'path';
|
|
5
|
+
import { StickerTypes } from '../types/StickerTypes.js';
|
|
6
|
+
import TextOnGif from './textOnGif.js';
|
|
7
|
+
/**
|
|
8
|
+
* Converts a video file to an animated GIF with optional text overlay
|
|
9
|
+
* @param options Configuration options for the conversion
|
|
10
|
+
* @returns Promise<Buffer> The resulting GIF as a buffer
|
|
11
|
+
*/
|
|
12
|
+
const videoToGif = async ({ buffer, extType, type, text = '', maxDuration = 7, maxRetries = 3 }) => {
|
|
13
|
+
const generateTempFilename = () => join(tmpdir(), `${Math.random().toString(36).slice(2)}`);
|
|
14
|
+
const cleanupFiles = async (...files) => {
|
|
15
|
+
await Promise.all(files.map(file => fs.unlink(file).catch(() => { })));
|
|
16
|
+
};
|
|
17
|
+
const processVideo = async (attempt) => {
|
|
18
|
+
const inputFile = `${generateTempFilename()}.${extType}`;
|
|
19
|
+
const outputFile = `${generateTempFilename()}.gif`;
|
|
20
|
+
try {
|
|
21
|
+
// Write input buffer to temporary file
|
|
22
|
+
await fs.writeFile(inputFile, buffer);
|
|
23
|
+
// Determine scaling and cropping parameters based on type
|
|
24
|
+
const shape = type === StickerTypes.SQUARE
|
|
25
|
+
? 'scale=320:-1:flags=lanczos,fps=10,crop=min(iw\\,ih):min(iw\\,ih)'
|
|
26
|
+
: 'scale=320:-1:flags=lanczos,fps=20';
|
|
27
|
+
// Process video with ffmpeg
|
|
28
|
+
await new Promise((resolve, reject) => {
|
|
29
|
+
ffmpeg(inputFile)
|
|
30
|
+
.inputFormat(extType)
|
|
31
|
+
.outputOptions([
|
|
32
|
+
'-vf', shape,
|
|
33
|
+
'-loop', '0',
|
|
34
|
+
'-lossless', '0',
|
|
35
|
+
'-t', maxDuration.toString(),
|
|
36
|
+
'-preset', 'ultrafast'
|
|
37
|
+
])
|
|
38
|
+
.toFormat('gif')
|
|
39
|
+
.save(outputFile)
|
|
40
|
+
.on('end', () => resolve())
|
|
41
|
+
.on('error', reject);
|
|
42
|
+
});
|
|
43
|
+
// Add text to GIF if required, or return the GIF buffer directly
|
|
44
|
+
const gifBuffer = text
|
|
45
|
+
? await TextOnGif(outputFile, text)
|
|
46
|
+
: await fs.readFile(outputFile);
|
|
47
|
+
// Clean up temporary files
|
|
48
|
+
await cleanupFiles(inputFile, outputFile);
|
|
49
|
+
return gifBuffer;
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
// Clean up temporary files
|
|
53
|
+
await cleanupFiles(inputFile, outputFile);
|
|
54
|
+
// Retry on failure up to the specified number of attempts
|
|
55
|
+
if (attempt < maxRetries) {
|
|
56
|
+
return processVideo(attempt + 1);
|
|
57
|
+
}
|
|
58
|
+
throw new Error(`Failed to convert video to GIF after ${maxRetries} attempts: ${error instanceof Error ? error.message : String(error)}`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
return processVideo(1);
|
|
62
|
+
};
|
|
63
|
+
export default videoToGif;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { Readable } from 'stream';
|
|
2
|
+
import fs from 'fs-extra';
|
|
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
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,19 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shibam/sticker-maker",
|
|
3
|
-
"version": "1.2.
|
|
4
|
-
"
|
|
3
|
+
"version": "1.2.15",
|
|
4
|
+
"description": "A package for creating stickers",
|
|
5
|
+
"main": "dist/index.js",
|
|
5
6
|
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
6
10
|
"scripts": {
|
|
7
|
-
"
|
|
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"
|
|
8
18
|
},
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
|
|
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
|
+
],
|
|
13
34
|
"dependencies": {
|
|
35
|
+
"canvas": "^2.11.2",
|
|
14
36
|
"file-type": "^20.0.0",
|
|
37
|
+
"fluent-ffmpeg": "^2.1.3",
|
|
15
38
|
"fs-extra": "^11.3.0",
|
|
16
|
-
"node-webpmux": "3.
|
|
17
|
-
"sharp": "0.30.0"
|
|
39
|
+
"node-webpmux": "^3.2.0",
|
|
40
|
+
"sharp": "0.30.0",
|
|
41
|
+
"text-on-gif": "^2.0.13"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/fluent-ffmpeg": "^2.1.27",
|
|
45
|
+
"@types/fs-extra": "^11.0.4",
|
|
46
|
+
"@types/node": "^20.17.14",
|
|
47
|
+
"@types/sharp": "^0.28.5",
|
|
48
|
+
"tsx": "^4.7.1",
|
|
49
|
+
"typescript": "^5.4.5"
|
|
18
50
|
}
|
|
19
51
|
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
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.
|
package/index.js
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import Exif from "./utils/changeMetaInfo.js";
|
|
2
|
-
import MediaConverter from "./utils/convert.js";
|
|
3
|
-
import extractMetadata from "./utils/extractMetaInfo.js";
|
|
4
|
-
import fs from "fs-extra";
|
|
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.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
|
-
const inputBuffer = await this.processImage(this.image);
|
|
102
|
-
|
|
103
|
-
const webpBuffer = await this.converter.convertToWebp(inputBuffer);
|
|
104
|
-
|
|
105
|
-
const exif = new Exif({
|
|
106
|
-
id: this.id,
|
|
107
|
-
pack: this.pack,
|
|
108
|
-
author: this.author,
|
|
109
|
-
category: this.category,
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
this.buffer = await exif.add(webpBuffer);
|
|
113
|
-
return this.buffer;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async toBuffer() {
|
|
117
|
-
return await this.build();
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async metadata() {
|
|
121
|
-
if (!this.buffer) {
|
|
122
|
-
await this.build();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return await extractMetadata(this.buffer);
|
|
126
|
-
}
|
|
127
|
-
}
|
package/utils/changeMetaInfo.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
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
|
-
image =
|
|
31
|
-
image instanceof Image.Image
|
|
32
|
-
? image
|
|
33
|
-
: await (async () => {
|
|
34
|
-
const img = new Image.Image()
|
|
35
|
-
await img.load(image)
|
|
36
|
-
return img
|
|
37
|
-
})();
|
|
38
|
-
image.exif = exif
|
|
39
|
-
return await image.save(null)
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export default Exif;
|
package/utils/convert.js
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { exec as execCallback } from "child_process";
|
|
2
|
-
import fs from "fs-extra";
|
|
3
|
-
import { tmpdir } from "os";
|
|
4
|
-
import { promisify } from "util";
|
|
5
|
-
import { fileTypeFromBuffer } from "file-type";
|
|
6
|
-
import sharp from "sharp";
|
|
7
|
-
const exec = promisify(execCallback);
|
|
8
|
-
|
|
9
|
-
export default class MediaConverter {
|
|
10
|
-
constructor(options = {}) {
|
|
11
|
-
this.fps = 12;
|
|
12
|
-
this.quality = options.quality ?? 10;
|
|
13
|
-
this.width = options.width ?? 320;
|
|
14
|
-
this.mime = null;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
async convertToWebp(buffer) {
|
|
18
|
-
const fileType = await fileTypeFromBuffer(buffer);
|
|
19
|
-
if (!fileType) throw new Error("Invalid file type");
|
|
20
|
-
if (fileType.ext === "webp") return buffer;
|
|
21
|
-
this.mime = fileType.mime;
|
|
22
|
-
|
|
23
|
-
if (this.mime.startsWith("video/")) {
|
|
24
|
-
const gif = await this.videoToGif(buffer);
|
|
25
|
-
return await this.ToWebp(gif);
|
|
26
|
-
} else if (this.mime === "image/gif") {
|
|
27
|
-
return await this.ToWebp(buffer);
|
|
28
|
-
} else if (this.mime.startsWith("image/")) {
|
|
29
|
-
return await this.ToWebp(buffer);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
throw new Error(`Unsupported file type: ${this.mime}`);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
videoToGif = async (data) => {
|
|
36
|
-
const filename = `${tmpdir()}/${Math.random().toString(36).substring(2)}`;
|
|
37
|
-
const videoPath = `${filename}.mp4`;
|
|
38
|
-
const gifPath = `${filename}.gif`;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
// Write the input video buffer to a temporary file
|
|
42
|
-
await fs.writeFile(videoPath, data);
|
|
43
|
-
|
|
44
|
-
// Execute FFmpeg command to convert video to GIF with lossless option
|
|
45
|
-
const ffmpegCmd = `ffmpeg -i "${videoPath}" -vf "fps=15,scale=320:-1:flags=lanczos" -loop 0 -lossless 0 "${gifPath}"`;
|
|
46
|
-
await exec(ffmpegCmd);
|
|
47
|
-
|
|
48
|
-
// Read the resulting GIF as a buffer
|
|
49
|
-
const gifBuffer = await fs.readFile(gifPath);
|
|
50
|
-
|
|
51
|
-
// Clean up temporary files
|
|
52
|
-
await Promise.all([
|
|
53
|
-
fs.unlink(videoPath).catch(() => {}),
|
|
54
|
-
fs.unlink(gifPath).catch(() => {}),
|
|
55
|
-
]);
|
|
56
|
-
|
|
57
|
-
return gifBuffer;
|
|
58
|
-
} catch (error) {
|
|
59
|
-
// Clean up files in case of an error
|
|
60
|
-
await Promise.all([
|
|
61
|
-
fs.unlink(videoPath).catch(() => {}),
|
|
62
|
-
fs.unlink(gifPath).catch(() => {}),
|
|
63
|
-
]);
|
|
64
|
-
throw new Error(`Failed to convert video to GIF: ${error.message}`);
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
async ToWebp(buffer) {
|
|
68
|
-
const fileType = await fileTypeFromBuffer(buffer);
|
|
69
|
-
if (!fileType) throw new Error("Invalid file type");
|
|
70
|
-
|
|
71
|
-
const mimeType = fileType.mime;
|
|
72
|
-
const isAnimated = mimeType?.includes("video") || mimeType?.includes("gif");
|
|
73
|
-
|
|
74
|
-
// Initialize sharp with animation support for GIFs or video frames
|
|
75
|
-
const res = sharp(buffer, { animated: isAnimated })
|
|
76
|
-
.toFormat("webp")
|
|
77
|
-
.resize(this.width, this.width, {
|
|
78
|
-
fit: sharp.fit.contain,
|
|
79
|
-
background: { r: 0, g: 0, b: 0, alpha: 0 }, // Transparent background
|
|
80
|
-
});
|
|
81
|
-
// Convert to WebP format with the specified quality
|
|
82
|
-
|
|
83
|
-
return await res
|
|
84
|
-
.webp({ quality: this.quality, lossless: false }) // Lossless for GIFs or animations
|
|
85
|
-
.toBuffer();
|
|
86
|
-
}
|
|
87
|
-
}
|
package/utils/extractMetaInfo.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
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
|