Initialize the admin app with banner management for app sections.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
const MAX_EDGE = 960
|
||||
const JPEG_QUALITY = 0.82
|
||||
|
||||
export async function fileToCatalogImage(file: File): Promise<string> {
|
||||
if (!file.type.startsWith('image/')) {
|
||||
throw new Error('فقط فایل تصویری مجاز است.')
|
||||
}
|
||||
if (file.size > 8 * 1024 * 1024) {
|
||||
throw new Error('حجم تصویر نباید بیشتر از ۸ مگابایت باشد.')
|
||||
}
|
||||
|
||||
const dataUrl = await readFileAsDataUrl(file)
|
||||
return resizeDataUrl(dataUrl)
|
||||
}
|
||||
|
||||
function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result ?? ''))
|
||||
reader.onerror = () => reject(new Error('خواندن تصویر ناموفق بود.'))
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
function resizeDataUrl(src: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const image = new Image()
|
||||
image.onload = () => {
|
||||
const scale = Math.min(1, MAX_EDGE / Math.max(image.width, image.height))
|
||||
const width = Math.max(1, Math.round(image.width * scale))
|
||||
const height = Math.max(1, Math.round(image.height * scale))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) {
|
||||
reject(new Error('پردازش تصویر ناموفق بود.'))
|
||||
return
|
||||
}
|
||||
ctx.drawImage(image, 0, 0, width, height)
|
||||
resolve(canvas.toDataURL('image/jpeg', JPEG_QUALITY))
|
||||
}
|
||||
image.onerror = () => reject(new Error('تصویر نامعتبر است.'))
|
||||
image.src = src
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user