Determine image dimensions for uploads

This commit is contained in:
Maximilian Harz 2025-06-09 11:49:02 +02:00
parent 0aa64a1a9c
commit cc9d3c76bb
2 changed files with 37 additions and 3 deletions

View File

@ -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,
},
},
],

View File

@ -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')
}
})