From 726943c994e5ae228023a96363f31460dbef07b1 Mon Sep 17 00:00:00 2001
From: Mqdd <ahmadmiqdad27@gmail.com>
Date: Mon, 15 Dec 2025 13:25:38 +0700
Subject: <Miqdad> compress image

---
 app/lib/camera/component/dispatchCamera.tsx | 61 ++++++++++++++++++++++++++---
 1 file changed, 56 insertions(+), 5 deletions(-)

(limited to 'app/lib/camera/component/dispatchCamera.tsx')

diff --git a/app/lib/camera/component/dispatchCamera.tsx b/app/lib/camera/component/dispatchCamera.tsx
index 2591413..6780c12 100644
--- a/app/lib/camera/component/dispatchCamera.tsx
+++ b/app/lib/camera/component/dispatchCamera.tsx
@@ -3,17 +3,68 @@ import useCameraStore from "../hooks/useCameraStore";
 import { IconButton } from "@mui/material";
 import { LocalShipping } from "@mui/icons-material";
 
+const MAX_WIDTH = 1024;
+const JPEG_QUALITY = 0.7;
+
 const DispatchCamera: React.FC = () => {
   const { setImageDispatch } = useCameraStore();
-  const handleCapture = (event: React.ChangeEvent<HTMLInputElement>) => {
-    const file = event.target.files?.[0];
-    if (file) {
+
+  const compressImage = (file: File): Promise<string> => {
+    return new Promise((resolve, reject) => {
       const reader = new FileReader();
-      reader.onloadend = () => {
-        setImageDispatch(reader.result as string);
+
+      reader.onload = () => {
+        const img = new Image();
+        img.onload = () => {
+          let { width, height } = img;
+
+          if (width > MAX_WIDTH) {
+            height = (height * MAX_WIDTH) / width;
+            width = MAX_WIDTH;
+          }
+
+          const canvas = document.createElement("canvas");
+          canvas.width = width;
+          canvas.height = height;
+
+          const ctx = canvas.getContext("2d");
+          if (!ctx) {
+            reject("Canvas not supported");
+            return;
+          }
+
+          ctx.drawImage(img, 0, 0, width, height);
+
+          const compressedBase64 = canvas.toDataURL("image/jpeg", JPEG_QUALITY);
+
+          resolve(compressedBase64);
+        };
+
+        img.onerror = reject;
+        img.src = reader.result as string;
       };
+
+      reader.onerror = reject;
       reader.readAsDataURL(file);
+    });
+  };
+  const handleCapture = async (event: React.ChangeEvent<HTMLInputElement>) => {
+    const file = event.target.files?.[0];
+    if (!file) return;
+
+    try {
+      const compressesd = await compressImage(file);
+      setImageDispatch(compressesd);
+    } catch (err) {
+      console.error("Image compress failed", err);
     }
+    // if (file) {
+    //   const reader = new FileReader();
+    //   reader.onloadend = () => {
+    //     setImageDispatch(reader.result as string);
+    //   };
+    //   reader.readAsDataURL(file);
+    // }
   };
 
   return (
-- 
cgit v1.2.3

