feat: Compress PNG; detect and compare the size of compressed and uncompressed file
This commit is contained in:
parent
aea6659d0b
commit
99815e1af8
1 changed files with 13 additions and 7 deletions
|
@ -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);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue