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