80 lines
2.6 KiB
JavaScript
80 lines
2.6 KiB
JavaScript
const MAX_WIDTH = 768;
|
|
const MAX_HEIGHT = 480;
|
|
const TARGET_BYTES = 500 * 1024;
|
|
const DEFAULT_QUALITY = 0.72;
|
|
const FALLBACK_QUALITY = 0.62;
|
|
|
|
async function decodeImage(file) {
|
|
if (typeof createImageBitmap === 'function') {
|
|
try {
|
|
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
|
return { source: bitmap, width: bitmap.width, height: bitmap.height, dispose: () => bitmap.close() };
|
|
} catch {
|
|
// Fall through to HTMLImageElement for browsers without ImageBitmap support.
|
|
}
|
|
}
|
|
|
|
const objectUrl = URL.createObjectURL(file);
|
|
try {
|
|
const image = await new Promise((resolve, reject) => {
|
|
const element = new Image();
|
|
element.onload = () => resolve(element);
|
|
element.onerror = () => reject(new Error('无法读取封面图片'));
|
|
element.src = objectUrl;
|
|
});
|
|
return {
|
|
source: image,
|
|
width: image.naturalWidth,
|
|
height: image.naturalHeight,
|
|
dispose: () => URL.revokeObjectURL(objectUrl),
|
|
};
|
|
} catch (error) {
|
|
URL.revokeObjectURL(objectUrl);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function canvasBlob(canvas, quality) {
|
|
return new Promise((resolve) => canvas.toBlob(resolve, 'image/webp', quality));
|
|
}
|
|
|
|
export async function compressCoverImage(file) {
|
|
if (file.size <= 0 || file.size > 5 * 1024 * 1024) return file;
|
|
|
|
let decoded;
|
|
try {
|
|
decoded = await decodeImage(file);
|
|
} catch {
|
|
return file;
|
|
}
|
|
|
|
try {
|
|
if (decoded.width <= 0 || decoded.height <= 0) return file;
|
|
const scale = Math.min(1, MAX_WIDTH / decoded.width, MAX_HEIGHT / decoded.height);
|
|
const width = Math.max(1, Math.round(decoded.width * scale));
|
|
const height = Math.max(1, Math.round(decoded.height * scale));
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = width;
|
|
canvas.height = height;
|
|
const context = canvas.getContext('2d');
|
|
if (!context) return file;
|
|
context.drawImage(decoded.source, 0, 0, width, height);
|
|
|
|
const candidates = [];
|
|
const normal = await canvasBlob(canvas, DEFAULT_QUALITY);
|
|
if (normal) candidates.push(normal);
|
|
if (normal && normal.size > TARGET_BYTES) {
|
|
const smaller = await canvasBlob(canvas, FALLBACK_QUALITY);
|
|
if (smaller) candidates.push(smaller);
|
|
}
|
|
const smallest = candidates.sort((a, b) => a.size - b.size)[0];
|
|
if (!smallest || smallest.type !== 'image/webp' || smallest.size >= file.size) return file;
|
|
const name = file.name.replace(/\.[^.]+$/, '') || 'cover';
|
|
return new File([smallest], `${name}.webp`, { type: 'image/webp', lastModified: file.lastModified });
|
|
} catch {
|
|
return file;
|
|
} finally {
|
|
decoded.dispose();
|
|
}
|
|
}
|