fix(system): photo rotate and reduce on browser-image-compression
This commit is contained in:
@@ -23,7 +23,6 @@
|
||||
"@capgo/capacitor-updater": "^8",
|
||||
"@zxing/browser": "^0.1.5",
|
||||
"@zxing/library": "^0.21.3",
|
||||
"browser-image-compression": "^2.0.2",
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"less": "^4.3.0",
|
||||
|
||||
Generated
-15
@@ -28,9 +28,6 @@ importers:
|
||||
'@zxing/library':
|
||||
specifier: ^0.21.3
|
||||
version: 0.21.3
|
||||
browser-image-compression:
|
||||
specifier: ^2.0.2
|
||||
version: 2.0.2
|
||||
echarts:
|
||||
specifier: ^6.0.0
|
||||
version: 6.1.0
|
||||
@@ -1424,9 +1421,6 @@ packages:
|
||||
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
browser-image-compression@2.0.2:
|
||||
resolution: {integrity: sha512-pBLlQyUf6yB8SmmngrcOw3EoS4RpQ1BcylI3T9Yqn7+4nrQTXJD4sJDe5ODnJdrvNMaio5OicFo75rDyJD2Ucw==}
|
||||
|
||||
buffer-crc32@0.2.13:
|
||||
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
|
||||
|
||||
@@ -2904,9 +2898,6 @@ packages:
|
||||
util-deprecate@1.0.2:
|
||||
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
|
||||
|
||||
uzip@0.20201231.0:
|
||||
resolution: {integrity: sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng==}
|
||||
|
||||
v8-compile-cache-lib@3.0.1:
|
||||
resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==}
|
||||
|
||||
@@ -4412,10 +4403,6 @@ snapshots:
|
||||
dependencies:
|
||||
fill-range: 7.1.1
|
||||
|
||||
browser-image-compression@2.0.2:
|
||||
dependencies:
|
||||
uzip: 0.20201231.0
|
||||
|
||||
buffer-crc32@0.2.13: {}
|
||||
|
||||
buffer-from@1.1.2: {}
|
||||
@@ -6052,8 +6039,6 @@ snapshots:
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
uzip@0.20201231.0: {}
|
||||
|
||||
v8-compile-cache-lib@3.0.1: {}
|
||||
|
||||
validator@13.15.35: {}
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
declare module "browser-image-compression" {
|
||||
export interface ImageCompressionOptions {
|
||||
alwaysKeepResolution?: boolean;
|
||||
exifOrientation?: number;
|
||||
fileType?: string;
|
||||
initialQuality?: number;
|
||||
libURL?: string;
|
||||
maxIteration?: number;
|
||||
maxSizeMB?: number;
|
||||
maxWidthOrHeight?: number;
|
||||
onProgress?: (progress: number) => void;
|
||||
preserveExif?: boolean;
|
||||
signal?: AbortSignal;
|
||||
useWebWorker?: boolean;
|
||||
}
|
||||
|
||||
export default function imageCompression(file: File, options: ImageCompressionOptions): Promise<File>;
|
||||
}
|
||||
@@ -1,37 +1,46 @@
|
||||
import imageCompression from "browser-image-compression";
|
||||
/** 单张照片压缩后的目标体积 */
|
||||
const TARGET_BYTES = 300 * 1024;
|
||||
|
||||
const PHOTO_MAX_SIZE_MB = 300 / 1024;
|
||||
const PHOTO_MAX_WIDTH_OR_HEIGHT = 1920;
|
||||
/** 长边上限,超过就等比缩小 */
|
||||
const MAX_EDGE = 1920;
|
||||
|
||||
/** 质量阶梯:从高往低试,命中目标体积就停 */
|
||||
const QUALITY_LIST = [.86, .78, .7, .62, .54, .46];
|
||||
|
||||
/** 兜底缩放的次数,质量降到最低仍超标时继续缩小尺寸 */
|
||||
const MAX_SCALE_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* 转为真正的 File,避免压缩库返回 Blob 后 FormData 使用默认文件名 blob。
|
||||
*/
|
||||
function normalizeUploadImageFile(source: File, compressed: Blob): File {
|
||||
if (compressed instanceof File && compressed.name) {
|
||||
return compressed;
|
||||
}
|
||||
|
||||
return new File([compressed], source.name || "upload-image", {
|
||||
type: compressed.type || source.type,
|
||||
lastModified: source.lastModified
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩上传图片,统一限制到 300 KB。
|
||||
* 压缩上传图片
|
||||
*
|
||||
* 用自己的 canvas 实现而不是 browser-image-compression:后者在 Web Worker 里用
|
||||
* `createImageBitmap` + `OffscreenCanvas` 解码,再把手写 EXIF 的方向标记改成 1。
|
||||
* 一旦 worker 里解出来的位图没有按 EXIF 摆正,存下来的照片就是"倒转 + 大片空白",
|
||||
* 而且不可逆。这里用 `<img>` 解码——浏览器会按 EXIF 摆正,`naturalWidth/naturalHeight`
|
||||
* 也是摆正后的尺寸,所以画到 canvas 上一定是对的。
|
||||
*
|
||||
* @param file 原始文件
|
||||
* @returns 压缩后的文件,非图片或压缩失败时原样返回
|
||||
*/
|
||||
export async function compressUploadImage(file: File): Promise<File> {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
return file;
|
||||
}
|
||||
|
||||
const compressedFile = await imageCompression(file, {
|
||||
maxSizeMB: PHOTO_MAX_SIZE_MB,
|
||||
maxWidthOrHeight: PHOTO_MAX_WIDTH_OR_HEIGHT,
|
||||
useWebWorker: true,
|
||||
initialQuality: .86
|
||||
});
|
||||
return normalizeUploadImageFile(file, compressedFile);
|
||||
try {
|
||||
const image = await loadImage(file);
|
||||
const blob = await encodeWithinTarget(image);
|
||||
if (!blob) {
|
||||
return file;
|
||||
}
|
||||
return new File([blob], fileName(file), {
|
||||
type: "image/jpeg",
|
||||
lastModified: file.lastModified
|
||||
});
|
||||
} catch {
|
||||
// 压缩是优化项,失败就传原图,不能让上传断掉
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,3 +53,67 @@ export async function compressUploadImageList(fileList: File[]): Promise<File[]>
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 解码图片,浏览器会自动应用 EXIF 方向 */
|
||||
function loadImage(file: File): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = URL.createObjectURL(file);
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(image);
|
||||
};
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("图片解码失败"));
|
||||
};
|
||||
image.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/** 逐级降质量、实在不行再降尺寸,直到体积达标 */
|
||||
async function encodeWithinTarget(image: HTMLImageElement): Promise<Blob | null> {
|
||||
const width = image.naturalWidth || image.width;
|
||||
const height = image.naturalHeight || image.height;
|
||||
let scale = Math.min(1, MAX_EDGE / Math.max(width, height));
|
||||
let last: Blob | null = null;
|
||||
|
||||
for (let attempt = 0; attempt < MAX_SCALE_ATTEMPTS; attempt += 1) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.round(width * scale));
|
||||
canvas.height = Math.max(1, Math.round(height * scale));
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) {
|
||||
return last;
|
||||
}
|
||||
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
for (const quality of QUALITY_LIST) {
|
||||
const blob = await toBlob(canvas, quality);
|
||||
if (!blob) {
|
||||
return last;
|
||||
}
|
||||
last = blob;
|
||||
if (blob.size <= TARGET_BYTES) {
|
||||
return blob;
|
||||
}
|
||||
}
|
||||
// 质量到底还超标,缩小尺寸再来一轮
|
||||
scale *= .8;
|
||||
}
|
||||
|
||||
return last;
|
||||
}
|
||||
|
||||
/** canvas 转 JPEG,统一走 promise */
|
||||
function toBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob | null> {
|
||||
return new Promise(resolve => canvas.toBlob(blob => resolve(blob), "image/jpeg", quality));
|
||||
}
|
||||
|
||||
/** 保留原文件名,缺省时给一个带时间戳的 */
|
||||
function fileName(file: File): string {
|
||||
if (file.name) {
|
||||
return file.name;
|
||||
}
|
||||
return `upload-${Date.now()}.jpg`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user