272 lines
9.7 KiB
TypeScript
272 lines
9.7 KiB
TypeScript
/**
|
|
* Purpose: DEFAULT_MAX_IMAGE_SIZE supports image-upload.ts by holding or executing the default max image size page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
|
|
/**
|
|
* Purpose: AUTO_COMPRESS_TYPES supports image-upload.ts by holding or executing the auto compress types page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
|
|
|
|
/**
|
|
* Purpose: inferImageMimeType supports image-upload.ts by holding or executing the infer image mime type page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const inferImageMimeType = (file: File) => {
|
|
if (file.type) return file.type.toLowerCase()
|
|
const name = file.name.toLowerCase().split(/[?#]/)[0] || ''
|
|
if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg'
|
|
if (name.endsWith('.png')) return 'image/png'
|
|
if (name.endsWith('.webp')) return 'image/webp'
|
|
if (name.endsWith('.gif')) return 'image/gif'
|
|
return ''
|
|
}
|
|
|
|
/**
|
|
* Purpose: ImageCompressionResult supports image-upload.ts by holding or executing the image compression result page or API role.
|
|
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
export interface ImageCompressionResult {
|
|
file: File
|
|
originalSize: number
|
|
finalSize: number
|
|
compressed: boolean
|
|
converted: boolean
|
|
skippedReason?: string
|
|
}
|
|
|
|
/**
|
|
* Purpose: QUALITY_STEPS supports image-upload.ts by holding or executing the quality steps page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
|
|
/**
|
|
* Purpose: SCALE_STEPS supports image-upload.ts by holding or executing the scale steps page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
|
|
|
|
/**
|
|
* Purpose: loadImageElement supports image-upload.ts by holding or executing the load image element page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
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
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Purpose: canvasToBlob supports image-upload.ts by holding or executing the canvas to blob page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
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
|
|
)
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Purpose: getOutputExtension supports image-upload.ts by holding or executing the get output extension page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const getOutputExtension = (type: string) => {
|
|
if (type === 'image/png') {
|
|
return '.png'
|
|
}
|
|
if (type === 'image/webp') {
|
|
return '.webp'
|
|
}
|
|
return '.jpg'
|
|
}
|
|
|
|
/**
|
|
* Purpose: buildOutputName supports image-upload.ts by holding or executing the build output name page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
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}`
|
|
}
|
|
|
|
/**
|
|
* Purpose: drawImageToCanvas supports image-upload.ts by holding or executing the draw image to canvas page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
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
|
|
}
|
|
|
|
/**
|
|
* Purpose: toCompressedFile supports image-upload.ts by holding or executing the to compressed file page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
|
|
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
|
|
type: mimeType,
|
|
lastModified: sourceFile.lastModified
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Purpose: getPreferredMimeTypes supports image-upload.ts by holding or executing the get preferred mime types page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
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']
|
|
}
|
|
|
|
/**
|
|
* Purpose: formatFileSize supports image-upload.ts by holding or executing the format file size page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
export const formatFileSize = (bytes: number) => {
|
|
if (bytes >= 1024 * 1024) {
|
|
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
|
|
}
|
|
return `${(bytes / 1024).toFixed(0)}KB`
|
|
}
|
|
|
|
/**
|
|
* Purpose: compressImageIfNeeded supports image-upload.ts by holding or executing the compress image if needed page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
export const compressImageIfNeeded = async (
|
|
file: File,
|
|
maxSize = DEFAULT_MAX_IMAGE_SIZE
|
|
): Promise<ImageCompressionResult> => {
|
|
const sourceType = inferImageMimeType(file)
|
|
if (!sourceType.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(sourceType)) {
|
|
return {
|
|
file,
|
|
originalSize: file.size,
|
|
finalSize: file.size,
|
|
compressed: false,
|
|
converted: false,
|
|
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
|
|
}
|
|
}
|
|
|
|
const image = await loadImageElement(file)
|
|
const preferredMimeTypes = getPreferredMimeTypes(new File([file], file.name, { type: sourceType || file.type }))
|
|
let bestBlob: Blob | null = null
|
|
let bestMimeType = sourceType || 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
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Purpose: MAX_IMAGE_UPLOAD_SIZE supports image-upload.ts by holding or executing the max image upload size page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
|