chat.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import heic2any from "heic2any";
  2. export function compressImage(file: File, maxSize: number): Promise<string> {
  3. return new Promise((resolve, reject) => {
  4. const reader = new FileReader();
  5. reader.onload = (readerEvent: any) => {
  6. const image = new Image();
  7. image.onload = () => {
  8. let canvas = document.createElement("canvas");
  9. let ctx = canvas.getContext("2d");
  10. let width = image.width;
  11. let height = image.height;
  12. let quality = 0.9;
  13. let dataUrl;
  14. do {
  15. canvas.width = width;
  16. canvas.height = height;
  17. ctx?.clearRect(0, 0, canvas.width, canvas.height);
  18. ctx?.drawImage(image, 0, 0, width, height);
  19. dataUrl = canvas.toDataURL("image/jpeg", quality);
  20. if (dataUrl.length < maxSize) break;
  21. if (quality > 0.5) {
  22. // Prioritize quality reduction
  23. quality -= 0.1;
  24. } else {
  25. // Then reduce the size
  26. width *= 0.9;
  27. height *= 0.9;
  28. }
  29. } while (dataUrl.length > maxSize);
  30. resolve(dataUrl);
  31. };
  32. image.onerror = reject;
  33. image.src = readerEvent.target.result;
  34. };
  35. reader.onerror = reject;
  36. if (file.type.includes("heic")) {
  37. heic2any({ blob: file, toType: "image/jpeg" })
  38. .then((blob) => {
  39. reader.readAsDataURL(blob as Blob);
  40. })
  41. .catch((e) => {
  42. reject(e);
  43. });
  44. }
  45. reader.readAsDataURL(file);
  46. });
  47. }