197 lines
5.0 KiB
TypeScript
197 lines
5.0 KiB
TypeScript
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
|
|||
|
|
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
|
||
|
|
|
||
|
|
export interface ImageCompressionResult {
|
||
|
|
file: File
|
||
|
|
originalSize: number
|
||
|
|
finalSize: number
|
||
|
|
compressed: boolean
|
||
|
|
converted: boolean
|
||
|
|
skippedReason?: string
|
||
|
|
}
|
||
|
|
|
||
|
|
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
|
||
|
|
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
|
||
|
|
|
||
|
|
const loadImageElement = (file: File) => {
|
||
|
|
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||
|
|
const image = new Image()
|
||
|
|
const objectUrl = URL.createObjectURL(file)
|
||
|
|
|
||
|
|
image.onload = () => {
|
||
|
|
URL.revokeObjectURL(objectUrl)
|
||
|
|
resolve(image)
|
||
|
|
}
|
||
|
|
|
||
|
|
image.onerror = () => {
|
||
|
|
URL.revokeObjectURL(objectUrl)
|
||
|
|
reject(new Error('图片读取失败'))
|
||
|
|
}
|
||
|
|
|
||
|
|
image.src = objectUrl
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
|
||
|
|
return new Promise<Blob>((resolve, reject) => {
|
||
|
|
canvas.toBlob(
|
||
|
|
(blob) => {
|
||
|
|
if (!blob) {
|
||
|
|
reject(new Error('图片压缩失败'))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
resolve(blob)
|
||
|
|
},
|
||
|
|
type,
|
||
|
|
quality
|
||
|
|
)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
const getOutputExtension = (type: string) => {
|
||
|
|
if (type === 'image/png') {
|
||
|
|
return '.png'
|
||
|
|
}
|
||
|
|
if (type === 'image/webp') {
|
||
|
|
return '.webp'
|
||
|
|
}
|
||
|
|
return '.jpg'
|
||
|
|
}
|
||
|
|
|
||
|
|
const buildOutputName = (fileName: string, type: string) => {
|
||
|
|
const extension = getOutputExtension(type)
|
||
|
|
const dotIndex = fileName.lastIndexOf('.')
|
||
|
|
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
|
||
|
|
return `${baseName}${extension}`
|
||
|
|
}
|
||
|
|
|
||
|
|
const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
|
||
|
|
const canvas = document.createElement('canvas')
|
||
|
|
canvas.width = width
|
||
|
|
canvas.height = height
|
||
|
|
|
||
|
|
const context = canvas.getContext('2d')
|
||
|
|
if (!context) {
|
||
|
|
throw new Error('无法初始化图片压缩画布')
|
||
|
|
}
|
||
|
|
|
||
|
|
if (mimeType !== 'image/png') {
|
||
|
|
context.fillStyle = '#ffffff'
|
||
|
|
context.fillRect(0, 0, width, height)
|
||
|
|
}
|
||
|
|
|
||
|
|
context.drawImage(image, 0, 0, width, height)
|
||
|
|
return canvas
|
||
|
|
}
|
||
|
|
|
||
|
|
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
|
||
|
|
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
|
||
|
|
type: mimeType,
|
||
|
|
lastModified: Date.now()
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
const getPreferredMimeTypes = (file: File) => {
|
||
|
|
if (file.type === 'image/png') {
|
||
|
|
return ['image/png', 'image/jpeg']
|
||
|
|
}
|
||
|
|
if (file.type === 'image/webp') {
|
||
|
|
return ['image/webp', 'image/jpeg']
|
||
|
|
}
|
||
|
|
return ['image/jpeg']
|
||
|
|
}
|
||
|
|
|
||
|
|
export const formatFileSize = (bytes: number) => {
|
||
|
|
if (bytes >= 1024 * 1024) {
|
||
|
|
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
|
||
|
|
}
|
||
|
|
return `${(bytes / 1024).toFixed(0)}KB`
|
||
|
|
}
|
||
|
|
|
||
|
|
export const compressImageIfNeeded = async (
|
||
|
|
file: File,
|
||
|
|
maxSize = DEFAULT_MAX_IMAGE_SIZE
|
||
|
|
): Promise<ImageCompressionResult> => {
|
||
|
|
if (!file.type.startsWith('image/')) {
|
||
|
|
return {
|
||
|
|
file,
|
||
|
|
originalSize: file.size,
|
||
|
|
finalSize: file.size,
|
||
|
|
compressed: false,
|
||
|
|
converted: false,
|
||
|
|
skippedReason: '仅支持图片文件上传'
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (file.size <= maxSize) {
|
||
|
|
return {
|
||
|
|
file,
|
||
|
|
originalSize: file.size,
|
||
|
|
finalSize: file.size,
|
||
|
|
compressed: false,
|
||
|
|
converted: false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!AUTO_COMPRESS_TYPES.has(file.type)) {
|
||
|
|
return {
|
||
|
|
file,
|
||
|
|
originalSize: file.size,
|
||
|
|
finalSize: file.size,
|
||
|
|
compressed: false,
|
||
|
|
converted: false,
|
||
|
|
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const image = await loadImageElement(file)
|
||
|
|
const preferredMimeTypes = getPreferredMimeTypes(file)
|
||
|
|
let bestBlob: Blob | null = null
|
||
|
|
let bestMimeType = file.type
|
||
|
|
|
||
|
|
for (const scale of SCALE_STEPS) {
|
||
|
|
const width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||
|
|
const height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||
|
|
|
||
|
|
for (const mimeType of preferredMimeTypes) {
|
||
|
|
const canvas = drawImageToCanvas(image, width, height, mimeType)
|
||
|
|
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
|
||
|
|
|
||
|
|
for (const quality of qualitySteps) {
|
||
|
|
const blob = await canvasToBlob(canvas, mimeType, quality)
|
||
|
|
|
||
|
|
if (!bestBlob || blob.size < bestBlob.size) {
|
||
|
|
bestBlob = blob
|
||
|
|
bestMimeType = mimeType
|
||
|
|
}
|
||
|
|
|
||
|
|
if (blob.size <= maxSize) {
|
||
|
|
const compressedFile = toCompressedFile(blob, file, mimeType)
|
||
|
|
return {
|
||
|
|
file: compressedFile,
|
||
|
|
originalSize: file.size,
|
||
|
|
finalSize: blob.size,
|
||
|
|
compressed: true,
|
||
|
|
converted: mimeType !== file.type
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!bestBlob) {
|
||
|
|
throw new Error('图片压缩失败')
|
||
|
|
}
|
||
|
|
|
||
|
|
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
|
||
|
|
return {
|
||
|
|
file: compressedFile,
|
||
|
|
originalSize: file.size,
|
||
|
|
finalSize: bestBlob.size,
|
||
|
|
compressed: true,
|
||
|
|
converted: bestMimeType !== file.type
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
|