From 2298be0e6ba4c828154efbfc3cb68b1aeea1ab1a Mon Sep 17 00:00:00 2001 From: Mary Hipp Date: Tue, 20 Aug 2024 13:02:25 -0400 Subject: [PATCH] fix(ui): error handling if unable to convert image URL to blob --- .../src/common/util/convertImageUrlToBlob.ts | 22 ++++++++++++------- .../StylePresetForm/StylePresetModal.tsx | 10 ++++++--- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/invokeai/frontend/web/src/common/util/convertImageUrlToBlob.ts b/invokeai/frontend/web/src/common/util/convertImageUrlToBlob.ts index 42fdd46609..44062fa025 100644 --- a/invokeai/frontend/web/src/common/util/convertImageUrlToBlob.ts +++ b/invokeai/frontend/web/src/common/util/convertImageUrlToBlob.ts @@ -8,7 +8,7 @@ import { $authToken } from 'app/store/nanostores/authToken'; */ export const convertImageUrlToBlob = async (url: string) => - new Promise((resolve) => { + new Promise((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((resolve) => { - canvas.toBlob(function (blob) { - resolve(blob); - }, 'image/png'); - }) - ); + 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; }); diff --git a/invokeai/frontend/web/src/features/stylePresets/components/StylePresetForm/StylePresetModal.tsx b/invokeai/frontend/web/src/features/stylePresets/components/StylePresetForm/StylePresetModal.tsx index cccae93c18..5ae1db7af9 100644 --- a/invokeai/frontend/web/src/features/stylePresets/components/StylePresetForm/StylePresetModal.tsx +++ b/invokeai/frontend/web/src/features/stylePresets/components/StylePresetForm/StylePresetModal.tsx @@ -48,9 +48,13 @@ export const StylePresetModal = () => { } else { let file = null; if (data.imageUrl) { - const blob = await convertImageUrlToBlob(data.imageUrl); - if (blob) { - file = new File([blob], 'style_preset.png', { type: 'image/png' }); + try { + const blob = await convertImageUrlToBlob(data.imageUrl); + if (blob) { + file = new File([blob], 'style_preset.png', { type: 'image/png' }); + } + } catch (error) { + // do nothing } } setFormData({