PluginProbe
Extendify / 2.2.0
Extendify v2.2.0
3.2.0 3.1.6 3.1.5 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 3.0.6 3.0.5 3.0.4 trunk 0.1.0 0.10.0 0.10.1 0.10.2 0.11.0 0.11.1 0.2.0 0.3.0 0.3.1 0.4.0 0.5.0 0.6.0 0.7.0 All 126 releases
extendify / src / Shared / utils / resize-image.js

resize-image.js in Extendify 2.2.0, at src/Shared/utils/resize-image.js

57 lines 1.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * Resize an image to the specified dimensions.
3 *
4 * @param {string} imageUrl - The source URL or blob URL of the image.
5 * @param {Object} options - Configuration options.
6 * @param {{ width: number, height: number }} options.size - Required size (e.g., { width: 64, height: 64 }).
7 * @param {string} [options.mimeType='image/png'] - Output format (e.g., 'image/png', 'image/webp').
8 * @returns {Promise<string>} - A blob URL of the resized image.
9 *
10 * @throws Will throw an error if imageUrl or size is invalid, or if resizing fails.
11 */
12 export const resizeImage = async (imageUrl, options = {}) => {
13 const { size, mimeType = 'image/png' } = options;
14
15 if (
16 !imageUrl ||
17 !size ||
18 typeof size.width !== 'number' ||
19 typeof size.height !== 'number' ||
20 size.width <= 0 ||
21 size.height <= 0
22 ) {
23 throw new Error('Invalid imageUrl or size dimensions');
24 }
25
26 const img = await loadImage(imageUrl);
27 const canvas = document.createElement('canvas');
28 canvas.width = size.width;
29 canvas.height = size.height;
30
31 const ctx = canvas.getContext('2d');
32 ctx.clearRect(0, 0, size.width, size.height);
33 ctx.drawImage(img, 0, 0, size.width, size.height);
34
35 return new Promise((resolve) => {
36 canvas.toBlob(
37 (blob) => {
38 if (!blob) {
39 throw new Error('Failed to create blob from canvas');
40 }
41 resolve(URL.createObjectURL(blob));
42 },
43 mimeType,
44 0.95,
45 );
46 });
47 };
48
49 const loadImage = (src) =>
50 new Promise((resolve, reject) => {
51 const img = new Image();
52 img.crossOrigin = 'anonymous';
53 img.onload = () => resolve(img);
54 img.onerror = reject;
55 img.src = src;
56 });
57