feat: Compress PNG; detect and compare the size of compressed and uncompressed file

This commit is contained in:
Lhcfl 2024-04-14 11:51:41 +08:00
parent aea6659d0b
commit 99815e1af8

View file

@ -18,6 +18,7 @@ export const uploads = ref<Uploading[]>([]);
const compressTypeMap = { const compressTypeMap = {
"image/jpeg": { quality: 0.85, mimeType: "image/jpeg" }, "image/jpeg": { quality: 0.85, mimeType: "image/jpeg" },
"image/png": { quality: 0.85, mimeType: "image/jpeg" },
"image/webp": { quality: 0.85, mimeType: "image/png" }, "image/webp": { quality: 0.85, mimeType: "image/png" },
"image/svg+xml": { quality: 1, mimeType: "image/png" }, "image/svg+xml": { quality: 1, mimeType: "image/png" },
} as const; } as const;
@ -52,7 +53,7 @@ export function uploadFile(
uploads.value.push(ctx); uploads.value.push(ctx);
let resizedImage: any; let resizedImage: Blob | undefined;
if (!keepOriginal && file.type in compressTypeMap) { if (!keepOriginal && file.type in compressTypeMap) {
const imgConfig = compressTypeMap[file.type]; const imgConfig = compressTypeMap[file.type];
@ -65,12 +66,17 @@ export function uploadFile(
try { try {
resizedImage = await readAndCompressImage(file, config); resizedImage = await readAndCompressImage(file, config);
ctx.name = if (resizedImage.size > file.size) {
file.type !== imgConfig.mimeType // if compression made the picture larger, give up compression
? `${ctx.name}.${ resizedImage = undefined;
mimeTypeMap[compressTypeMap[file.type].mimeType] } else {
}` ctx.name =
: ctx.name; file.type !== imgConfig.mimeType
? `${ctx.name}.${
mimeTypeMap[compressTypeMap[file.type].mimeType]
}`
: ctx.name;
}
} catch (err) { } catch (err) {
console.error("Failed to resize image", err); console.error("Failed to resize image", err);
} }