From cc9d3c76bbd7a075bbe24381d53dc19ead411353 Mon Sep 17 00:00:00 2001 From: Maximilian Harz Date: Mon, 9 Jun 2025 11:49:02 +0200 Subject: [PATCH] Determine image dimensions for uploads --- .../Profile/Subcomponents/GalleryForm.tsx | 10 +++++-- src/Utils/getImageDimensions.ts | 30 +++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 src/Utils/getImageDimensions.ts diff --git a/src/Components/Profile/Subcomponents/GalleryForm.tsx b/src/Components/Profile/Subcomponents/GalleryForm.tsx index fbb67450..37c533b2 100644 --- a/src/Components/Profile/Subcomponents/GalleryForm.tsx +++ b/src/Components/Profile/Subcomponents/GalleryForm.tsx @@ -6,6 +6,7 @@ import { useDropzone } from 'react-dropzone' import { useAppState } from '#components/AppShell/hooks/useAppState' import DialogModal from '#components/Templates/DialogModal' +import { getImageDimensions } from '#utils/getImageDimensions' import type { FormState } from '#types/FormState' @@ -38,8 +39,11 @@ export const GalleryForm = ({ state, setState }: Props) => { const uploads = acceptedFiles.map(async (file) => { const compressedFile = await imageCompression(file, compressionOptions) + const { width, height } = await getImageDimensions(compressedFile) return { - asset: await appState.assetsApi.upload(compressedFile, 'gallery'), + width, + height, + asset: await appState.assetsApi.upload(compressedFile, file.name), name: file.name, } }) @@ -52,8 +56,8 @@ export const GalleryForm = ({ state, setState }: Props) => { { directus_files_id: { id: upload.asset.id, - width: 0, - height: 0, + width: upload.width, + height: upload.height, }, }, ], diff --git a/src/Utils/getImageDimensions.ts b/src/Utils/getImageDimensions.ts new file mode 100644 index 00000000..7d5b36ae --- /dev/null +++ b/src/Utils/getImageDimensions.ts @@ -0,0 +1,30 @@ +export const getImageDimensions = ( + file: File, +): Promise<{ + width: number + height: number +}> => + // eslint-disable-next-line promise/avoid-new + new Promise((resolve, reject) => { + try { + const fileReader = new FileReader() + + fileReader.onload = () => { + const img = new Image() + + img.onload = function () { + resolve({ + width: img.width, + height: img.height, + }) + } + + img.src = fileReader.result as string // is the data URL because called with readAsDataURL + } + + fileReader.readAsDataURL(file) + } catch (error) { + reject(error) + throw new Error('Error reading image file') + } + })