fix(ui): error handling if unable to convert image URL to blob

This commit is contained in:
Mary Hipp 2024-08-20 13:02:25 -04:00 committed by psychedelicious
parent 63494dfca7
commit 2298be0e6b
2 changed files with 21 additions and 11 deletions

View File

@ -8,7 +8,7 @@ import { $authToken } from 'app/store/nanostores/authToken';
*/
export const convertImageUrlToBlob = async (url: string) =>
new Promise<Blob | null>((resolve) => {
new Promise<Blob | null>((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
@ -17,17 +17,23 @@ export const convertImageUrlToBlob = async (url: string) =>
const context = canvas.getContext('2d');
if (!context) {
reject(new Error('Failed to get canvas context'));
return;
}
context.drawImage(img, 0, 0);
resolve(
new Promise<Blob | null>((resolve) => {
canvas.toBlob(function (blob) {
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('Failed to convert image to blob'));
}
}, 'image/png');
})
);
};
img.onerror = () => {
reject(new Error('Image failed to load. The URL may be invalid or the object may not exist.'));
};
img.crossOrigin = $authToken.get() ? 'use-credentials' : 'anonymous';
img.src = url;
});

View File

@ -48,10 +48,14 @@ export const StylePresetModal = () => {
} else {
let file = null;
if (data.imageUrl) {
try {
const blob = await convertImageUrlToBlob(data.imageUrl);
if (blob) {
file = new File([blob], 'style_preset.png', { type: 'image/png' });
}
} catch (error) {
// do nothing
}
}
setFormData({
...data,