Welcome folks today in this blog post we will be resizing images
in browser using the react-image-file-resizer
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a react.js
project using the below command
npx create-react-app sampleapp
cd sampleapp
And now you need to install the below library using the npm
command as shown below
npm i react-image-file-resizer
And now you need to see the directory structure
of the react.js app as shown below
And now you need to edit the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import "./styles.css"; import { useState } from "react"; import Resizer from "react-image-file-resizer"; export default function App() { const [img, setImg] = useState(""); return ( <div className="App"> <input type="file" onChange={fileChangedHandler} /> <img src={img} alt="" /> </div> ); } |
As you can see we are having the input
file element where we allow the user to upload the images
to resize and then we have the img
element to resize
and display it inside the browser. And also you can see that we have attached the onChange
event listener where we are executing the method called fileChangedHandler
. And also for storing the selected image we are also importing the useState
hook and then we are declaring the state
variable for img
using the useState
hook.
And now we need to write the fileChangedHandler()
method as shown below
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 |
const fileChangedHandler = (e) => { let fileInput = false; if (e.target.files[0]) { console.log(e.target.files[0]); fileInput = true; } if (fileInput) { try { Resizer.imageFileResizer( e.target.files[0], 1500, 1000, "JPEG", 100, 0, (uri) => { console.log(uri); setImg(uri); }, "base64", 200, 200 ); } catch (err) { console.log(err); } } }; |
As you can see inside the above method we are getting the user selected
image using the e.target.files[0]
property. And then we are using the imageFileResizer()
method to resize the image and inside this method we are passing the actual image to resize
as an argument and then we are passing the width
and height
of the image to resize to. And then we are using the setImg()
hook method to display the resized
image.