| 3 | import { Jimp } from "jimp"; |
| 4 | |
| 5 | export function GrayscaleExample() { |
| 6 | const [selectedFile, setSelectedFile] = useState(""); |
| 7 | const [output, setOutput] = React.useState(""); |
| 8 | |
| 9 | function handleFile(e: React.ChangeEvent<HTMLInputElement>) { |
| 10 | const file = e.target.files?.[0]; |
| 11 | |
| 12 | if (!file) { |
| 13 | return; |
| 14 | } |
| 15 | |
| 16 | const reader = new FileReader(); |
| 17 | |
| 18 | reader.onload = async (e) => { |
| 19 | const data = e.target?.result; |
| 20 | |
| 21 | if (!data || !(data instanceof ArrayBuffer)) { |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | // Manipulate images uploaded directly from the website. |
| 26 | const image = await Jimp.fromBuffer(data); |
| 27 | |
| 28 | image.greyscale(); |
| 29 | |
| 30 | setSelectedFile(URL.createObjectURL(file)); |
| 31 | setOutput(await image.getBase64("image/png")); |
| 32 | }; |
| 33 | |
| 34 | reader.readAsArrayBuffer(file); |
| 35 | } |
| 36 | |
| 37 | useEffect(() => { |
| 38 | // Or load images hosted on the same domain. |
| 39 | Jimp.read("/jimp/dice.png").then(async (image) => { |
| 40 | setSelectedFile(await image.getBase64("image/png")); |
| 41 | image.greyscale(); |
| 42 | setOutput(await image.getBase64("image/png")); |
| 43 | }); |
| 44 | }, []); |
| 45 | |
| 46 | return ( |
| 47 | <div> |
| 48 | {/* A file input that takes a png/jpeg */} |
| 49 | <input type="file" accept="image/*" onChange={handleFile} /> |
| 50 | |
| 51 | <div |
| 52 | style={{ |
| 53 | display: "flex", |
| 54 | alignItems: "center", |
| 55 | gap: 20, |
| 56 | width: "100%", |
| 57 | }} |
| 58 | > |
| 59 | {selectedFile && ( |
| 60 | <img |
| 61 | style={{ flex: 1, minWidth: 0, objectFit: "contain", margin: 0 }} |
| 62 | src={selectedFile} |