fix(system): photo rotate and reduce on browser-image-compression
This commit is contained in:
-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