image.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 图片压缩
  3. */
  4. export const compressImages = (params) => {
  5. const { list, imgKey = "thumb", maxWidth, sizeRatio, qualityRatio = 0.8, } = params;
  6. return Promise.all(list.map((item) => {
  7. return new Promise((resolve, reject) => {
  8. const img = new Image();
  9. img.crossOrigin = "anonymous"; // 设置 CORS 属性
  10. img.src = item[imgKey];
  11. img.onload = () => {
  12. const canvas = document.createElement("canvas");
  13. const ctx = canvas.getContext("2d");
  14. // 根据传入参数计算新的宽高
  15. let newWidth, newHeight;
  16. if (sizeRatio) {
  17. newWidth = img.width * sizeRatio;
  18. newHeight = img.height * sizeRatio;
  19. }
  20. else if (maxWidth) {
  21. newWidth = Math.min(maxWidth, img.width);
  22. newHeight = (newWidth / img.width) * img.height;
  23. }
  24. else {
  25. // 如果未指定比例或最大宽度,保持原尺寸
  26. newWidth = img.width;
  27. newHeight = img.height;
  28. }
  29. canvas.width = newWidth;
  30. canvas.height = newHeight;
  31. // 绘制压缩后的图像
  32. ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, newWidth, newHeight);
  33. canvas.toBlob((blob) => {
  34. if (blob) {
  35. const url = URL.createObjectURL(blob);
  36. resolve(Object.assign(Object.assign({}, item), { _thumb: url }));
  37. }
  38. else {
  39. reject(new Error("Blob 创建失败"));
  40. }
  41. }, "image/jpeg", qualityRatio);
  42. };
  43. img.onerror = () => {
  44. reject(new Error("图片加载失败:" + item[imgKey]));
  45. };
  46. });
  47. }));
  48. };