fix: png avatar upload as jpeg (#8665)

This commit is contained in:
非法操作 2024-09-23 15:33:06 +08:00 committed by GitHub
parent 86f90fd9ff
commit b37954b966
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 2 deletions

View File

@ -88,7 +88,7 @@ const AppIconPicker: FC<AppIconPickerProps> = ({
if (!imageCropInfo)
return
setUploading(true)
const blob = await getCroppedImg(imageCropInfo.tempUrl, imageCropInfo.croppedAreaPixels)
const blob = await getCroppedImg(imageCropInfo.tempUrl, imageCropInfo.croppedAreaPixels, imageCropInfo.fileName)
const file = new File([blob], imageCropInfo.fileName, { type: blob.type })
handleLocalFileUpload(file)
}

View File

@ -11,6 +11,23 @@ export function getRadianAngle(degreeValue: number) {
return (degreeValue * Math.PI) / 180
}
export function getMimeType(fileName: string): string {
const extension = fileName.split('.').pop()?.toLowerCase()
switch (extension) {
case 'png':
return 'image/png'
case 'jpg':
case 'jpeg':
return 'image/jpeg'
case 'gif':
return 'image/gif'
case 'webp':
return 'image/webp'
default:
return 'image/jpeg'
}
}
/**
* Returns the new bounding area of a rotated rectangle.
*/
@ -31,12 +48,14 @@ export function rotateSize(width: number, height: number, rotation: number) {
export default async function getCroppedImg(
imageSrc: string,
pixelCrop: { x: number; y: number; width: number; height: number },
fileName: string,
rotation = 0,
flip = { horizontal: false, vertical: false },
): Promise<Blob> {
const image = await createImage(imageSrc)
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const mimeType = getMimeType(fileName)
if (!ctx)
throw new Error('Could not create a canvas context')
@ -93,6 +112,6 @@ export default async function getCroppedImg(
resolve(file)
else
reject(new Error('Could not create a blob'))
}, 'image/jpeg')
}, mimeType)
})
}