chat.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { UPLOAD_URL } from "@/app/constant";
  2. import heic2any from "heic2any";
  3. export function compressImage(file: File, maxSize: number): Promise<string> {
  4. return new Promise((resolve, reject) => {
  5. const reader = new FileReader();
  6. reader.onload = (readerEvent: any) => {
  7. const image = new Image();
  8. image.onload = () => {
  9. let canvas = document.createElement("canvas");
  10. let ctx = canvas.getContext("2d");
  11. let width = image.width;
  12. let height = image.height;
  13. let quality = 0.9;
  14. let dataUrl;
  15. do {
  16. canvas.width = width;
  17. canvas.height = height;
  18. ctx?.clearRect(0, 0, canvas.width, canvas.height);
  19. ctx?.drawImage(image, 0, 0, width, height);
  20. dataUrl = canvas.toDataURL("image/jpeg", quality);
  21. if (dataUrl.length < maxSize) break;
  22. if (quality > 0.5) {
  23. // Prioritize quality reduction
  24. quality -= 0.1;
  25. } else {
  26. // Then reduce the size
  27. width *= 0.9;
  28. height *= 0.9;
  29. }
  30. } while (dataUrl.length > maxSize);
  31. resolve(dataUrl);
  32. };
  33. image.onerror = reject;
  34. image.src = readerEvent.target.result;
  35. };
  36. reader.onerror = reject;
  37. if (file.type.includes("heic")) {
  38. heic2any({ blob: file, toType: "image/jpeg" })
  39. .then((blob) => {
  40. reader.readAsDataURL(blob as Blob);
  41. })
  42. .catch((e) => {
  43. reject(e);
  44. });
  45. }
  46. reader.readAsDataURL(file);
  47. });
  48. }
  49. export function base64Image2Blob(base64Data: string, contentType: string) {
  50. const byteCharacters = atob(base64Data);
  51. const byteNumbers = new Array(byteCharacters.length);
  52. for (let i = 0; i < byteCharacters.length; i++) {
  53. byteNumbers[i] = byteCharacters.charCodeAt(i);
  54. }
  55. const byteArray = new Uint8Array(byteNumbers);
  56. return new Blob([byteArray], { type: contentType });
  57. }
  58. export function uploadImage(file: Blob): Promise<string> {
  59. const body = new FormData();
  60. body.append("file", file);
  61. return fetch(UPLOAD_URL, {
  62. method: "post",
  63. body,
  64. mode: "cors",
  65. credentials: "include",
  66. })
  67. .then((res) => res.json())
  68. .then((res) => {
  69. console.log("res", res);
  70. if (res?.code == 0 && res?.data) {
  71. return res?.data;
  72. }
  73. throw Error(`upload Error: ${res?.msg}`);
  74. });
  75. }
  76. export function removeImage(imageUrl: string) {
  77. return fetch(imageUrl, {
  78. method: "DELETE",
  79. mode: "cors",
  80. credentials: "include",
  81. });
  82. }