| 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 |
|