chat.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { CACHE_URL_PREFIX, 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. const heic2any = require("heic2any");
  39. heic2any({ blob: file, toType: "image/jpeg" })
  40. .then((blob) => {
  41. reader.readAsDataURL(blob as Blob);
  42. })
  43. .catch((e) => {
  44. reject(e);
  45. });
  46. }
  47. reader.readAsDataURL(file);
  48. });
  49. }
  50. export async function preProcessImageContent(
  51. content: RequestMessage["content"],
  52. ) {
  53. if (typeof content === "string") {
  54. return content;
  55. }
  56. const result = [];
  57. for (const part of content) {
  58. if (part?.type == "image_url" && part?.image_url?.url) {
  59. const url = await cacheImageToBase64Image(part?.image_url?.url);
  60. result.push({ type: part.type, image_url: { url } });
  61. } else {
  62. result.push({ ...part });
  63. }
  64. }
  65. return result;
  66. }
  67. const imageCaches = {};
  68. export function cacheImageToBase64Image(imageUrl: string) {
  69. if (imageUrl.includes(CACHE_URL_PREFIX)) {
  70. if (!imageCaches[imageUrl]) {
  71. const reader = new FileReader();
  72. return fetch(imageUrl, {
  73. method: "GET",
  74. mode: "cors",
  75. credentials: "include",
  76. })
  77. .then((res) => res.blob())
  78. .then(
  79. (blob) => (imageCaches[imageUrl] = compressImage(blob, 256 * 1024)),
  80. ); // compressImage
  81. }
  82. return Promise.resolve(imageCaches[imageUrl]);
  83. }
  84. return imageUrl;
  85. }
  86. export function base64Image2Blob(base64Data: string, contentType: string) {
  87. const byteCharacters = atob(base64Data);
  88. const byteNumbers = new Array(byteCharacters.length);
  89. for (let i = 0; i < byteCharacters.length; i++) {
  90. byteNumbers[i] = byteCharacters.charCodeAt(i);
  91. }
  92. const byteArray = new Uint8Array(byteNumbers);
  93. return new Blob([byteArray], { type: contentType });
  94. }
  95. export function uploadImage(file: File): Promise<string> {
  96. const body = new FormData();
  97. body.append("file", file);
  98. return fetch(UPLOAD_URL, {
  99. method: "post",
  100. body,
  101. mode: "cors",
  102. credentials: "include",
  103. })
  104. .then((res) => res.json())
  105. .then((res) => {
  106. console.log("res", res);
  107. if (res?.code == 0 && res?.data) {
  108. return res?.data;
  109. }
  110. throw Error(`upload Error: ${res?.msg}`);
  111. });
  112. }
  113. export function removeImage(imageUrl: string) {
  114. return fetch(imageUrl, {
  115. method: "DELETE",
  116. mode: "cors",
  117. credentials: "include",
  118. });
  119. }