In this we will learn how to compress an image offline using ReacJs
you can watch speedcode at youtube
for this we need to download a npm package browser-image-compression
npm install browser-image-compression --save
or
yarn add browser-image-compression
and import into your code
import imageCompression from 'browser-image-compression';
use to take input file image and then handle it using handleUpload.
<input type="file" onChange={handleUpload}/>
we need a state hook to save uplaoded file.
const [originalImage,setOriginalImage]=useState(null);
and also see preview we also need
const [uploadPreview,setUploadPreview]=useState("http://navparivartan.in/wp-content/uploads/2018/11/placeholder.png")
the url is dummyUrl to dispaly when image is not uploaded.
And to see whether is uploaded or not
const [uploaded,setUploaded]=useState(0);
Now handleUpload
const handleUpload=(e)=>{ setOriginalImage(e.target.files[0]) setUploadPreview(URL.createObjectURL(e.target.files[0])) setUploaded(1); }
use a button to compress and handle it
<button onClick={handleCompress}>Compress</button>
use compImage to store the path of compressed image.
[compImage,setCompImage]=useState("http://navparivartan.in/wp-content/uploads/2018/11/placeholder.png");
const handleCompress=e=>{ if(uploaded) { const options = { maxSizeMB: 2, maxWidthOrHeight: 500, useWebWorker: true, } imageCompression(originalImage,options).then(x=>{ let output=x; const dlink=URL.createObjectURL(output); setCompImage(dlink); console.log(x) }) } }
so the final code is
import React,{useState} from 'react' import './App.css' import imageCompression from 'browser-image-compression'; export default function App() { const [uploadPreview,setUploadPreview]=useState("http://navparivartan.in/wp-content/uploads/2018/11/placeholder.png") const [uploaded,setUploaded]=useState(0); const [originalImage,setOriginalImage]=useState(null); const [compImage,setCompImage]=useState("http://navparivartan.in/wp-content/uploads/2018/11/placeholder.png"); const handleUpload=(e)=>{ setOriginalImage(e.target.files[0]) setUploadPreview(URL.createObjectURL(e.target.files[0])) setUploaded(1); } const handleCompress=e=>{ if(uploaded) { const options = { maxSizeMB: 2, maxWidthOrHeight: 500, useWebWorker: true, } imageCompression(originalImage,options).then(x=>{ let output=x; const dlink=URL.createObjectURL(output); setCompImage(dlink); console.log(x) }) } } return ( <div> <h1>Image Compressor</h1> <div className="imgContainer"> <img src={uploadPreview} alt="Uplaod Preview"/> <input type="file" onChange={handleUpload}/> </div> <button onClick={handleCompress}>Compress</button> <div className="imgContainer"> <img src={compImage} alt="Compress Preview"/> <button ><a href={compImage} download="download">Download</a></button> </div> </div> ) }
Top comments (0)