summaryrefslogtreecommitdiff
path: root/app/lib/camera/component/dispatchCamera.tsx
diff options
context:
space:
mode:
authorMqdd <ahmadmiqdad27@gmail.com>2025-12-15 13:25:38 +0700
committerMqdd <ahmadmiqdad27@gmail.com>2025-12-15 13:25:38 +0700
commit726943c994e5ae228023a96363f31460dbef07b1 (patch)
treefab67fbeca4dfb70161feedd287e46adc6e34b5f /app/lib/camera/component/dispatchCamera.tsx
parentc02762ae157d167ae27bf34f6014abcb49deecc1 (diff)
<Miqdad> compress imageHEADmaster
Diffstat (limited to 'app/lib/camera/component/dispatchCamera.tsx')
-rw-r--r--app/lib/camera/component/dispatchCamera.tsx61
1 files changed, 56 insertions, 5 deletions
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 (