-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompressImage.ts
More file actions
97 lines (85 loc) · 2.67 KB
/
Copy pathcompressImage.ts
File metadata and controls
97 lines (85 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
export type CompressImageOptions = {
/**
* 最大宽度
*/
maxWidth?: number;
/**
* 最大高度
*/
maxHeight?: number;
/**
* 图片质量,仅有 image/jpeg 和 image/webp 类型时才有效
*/
quality?: number;
/**
* 图片类型, 默认为 image/jpeg,可选值为 image/png,image/webp;如果是 image/png,则quality参数无效,只能通过宽高来进行压缩
*/
imageType?: 'image/jpeg' | 'image/png' | 'image/webp';
};
/**
* 压缩图片
*/
function compressImage(file: File, options?: CompressImageOptions): Promise<Blob | null> {
const {
maxWidth = 1080,
maxHeight = 1080,
quality = 0.92,
imageType = 'image/jpeg',
} = options || {};
return new Promise((resolve, reject) => {
if (!file) {
console.error('未选择文件');
reject('未选择文件');
return;
}
const image = new Image();
const reader = new FileReader();
reader.onload = (e) => {
if (e.target && e.target.result) {
image.src = e.target.result as string;
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('无法获取 Canvas 上下文');
reject('无法获取 Canvas 上下文');
return;
}
// 计算调整后的宽度和高度,保持纵横比
let newWidth = image.width;
let newHeight = image.height;
// 只有当图片的宽度和高度都大于最大值时才需要进行分辨率的调整
if (newWidth > maxWidth && newHeight > maxHeight) {
if (newWidth < newHeight) {
newWidth = maxWidth;
newHeight = (image.height * maxWidth) / image.width;
} else {
newHeight = maxHeight;
newWidth = (image.width * maxHeight) / image.height;
}
}
// 设置 Canvas 大小并绘制图片
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(image, 0, 0, newWidth, newHeight);
// 将 Canvas 上的图像转换为 Blob
canvas.toBlob(
async (blob) => {
if (!blob) {
console.error('无法生成 Blob 对象');
reject('无法生成 Blob 对象');
return;
}
// 返回压缩后的 Blob
resolve(blob);
},
imageType,
quality,
); // quality 是 JPEG 压缩质量,可以根据需要调整
};
}
};
reader.readAsDataURL(file);
});
}
export default compressImage;