image.js 2.1 KB

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