blob: 6780c12da63f3169014d32a19b430e8b3966ed37 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
import React from "react";
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 compressImage = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
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 (
<div className="px-4 py-8 items-center border-2 rounded-md shadow-sm w-[49%] text-center ">
<input
type="file"
accept="image/*"
onChange={handleCapture}
className="hidden"
id="dispatchCameraInput"
/>
<label htmlFor="dispatchCameraInput" className="text-gray-600">
<IconButton
color="primary"
aria-label="upload picture"
component="span"
>
<LocalShipping fontSize="large" />
</IconButton>
<br />
Foto Dispatch
</label>
</div>
);
};
export default DispatchCamera;
|