|
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | + |
| 3 | +import { defaultFormats, defaultPlugins } from "jimp"; |
| 4 | +import webp from "@jimp/wasm-webp"; |
| 5 | +import { createJimp } from "@jimp/core"; |
| 6 | + |
| 7 | +const Jimp = createJimp({ |
| 8 | + formats: [...defaultFormats, webp], |
| 9 | + plugins: defaultPlugins, |
| 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 | + /> |
| 70 | + )} |
| 71 | + {output && ( |
| 72 | + <img |
| 73 | + style={{ flex: 1, minWidth: 0, objectFit: "contain", margin: 0 }} |
| 74 | + src={output} |
| 75 | + alt="Output" |
| 76 | + /> |
| 77 | + )} |
| 78 | + </div> |
| 79 | + </div> |
| 80 | + ); |
| 81 | +} |
0 commit comments