React js Resize Image Before Upload

React js Resize Image Before Upload

React resize image before upload; In this tutorial, you will learn how to resize, compress and crop images before uploading in react js app.

React Js Resize, Compress and Crop Image Size

Follow the following steps and resize, crop, and compress images before uploading in react js app:

  • Step 1 – Create React App
  • Step 2 – Install React Image Crop Package
  • Step 3 – Create Simple Image Upload with Preview Component
  • Step 4 – Add Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install React Image Crop Package

Execute the following command to install react image crop package into your react app:

npm install react-image-crop

Step 3 – Create Image Resize And Crop Component

Visit the src directory of your react js app and create image crop, resize and compress before uploading a form component named ImageResizeCropComponent.js. And add the following code into it:

import React from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
class ImageResizeCropComponent extends React.Component {
state = {
src: null,
crop: {
unit: '%',
width: 20,
aspect: 16 / 9
}
};
onFileChange = (e) => {
if (e.target.files && e.target.files.length > 0) {
const reader = new FileReader();
reader.addEventListener('load', () =>
this.setState({ src: reader.result })
);
reader.readAsDataURL(e.target.files[0]);
}
};
// If you setState the crop in here you should return false.
onImageLoaded = (image) => {
this.imageRef = image;
};
onCropComplete = (crop) => {
this.makeClientCrop(crop);
};
onCropChange = (crop, percentCrop) => {
// You could also use percentCrop:
// this.setState({ crop: percentCrop });
this.setState({ crop });
};
async makeClientCrop(crop) {
if (this.imageRef && crop.width && crop.height) {
const croppedImageUrl = await this.getCroppedImg(
this.imageRef,
crop,
'newFile.jpeg'
);
this.setState({ croppedImageUrl });
}
}
getCroppedImg(image, crop, fileName) {
const canvas = document.createElement('canvas');
const pixelRatio = window.devicePixelRatio;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
const ctx = canvas.getContext('2d');
canvas.width = crop.width * pixelRatio * scaleX;
canvas.height = crop.height * pixelRatio * scaleY;
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width * scaleX,
crop.height * scaleY
);
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (!blob) {
//reject(new Error('Canvas is empty'));
console.error('Canvas is empty');
return;
}
blob.name = fileName;
window.URL.revokeObjectURL(this.fileUrl);
this.fileUrl = window.URL.createObjectURL(blob);
resolve(this.fileUrl);
},
'image/jpeg',
1
);
});
}
render() {
const { crop, croppedImageUrl, src } = this.state;
return (
<div className="App">
<div>
<input type="file" accept="image/*" onChange={this.onFileChange} />
</div>
{src && (
<ReactCrop
src={src}
crop={crop}
ruleOfThirds
onImageLoaded={this.onImageLoaded}
onComplete={this.onCropComplete}
onChange={this.onCropChange}
/>
)}
{croppedImageUrl && (
<img alt="Crop" style={{ maxWidth: '100%' }} src={croppedImageUrl} />
)}
</div>
);
}
}
export default ImageResizeCropComponent;

Step 4 – Add Component in App.js

In this step, you need to add ImageUploadPreviewComponent.js file in src/App.js file:

import React from 'react';
import './App.css';
import ImageResize from './components/ImageResizeCropComponent';
function App() {
return (
<div className="App">
<ImageResizeCropComponent />
</div>
);
}
export default App;

Conclusion

React resize the image before upload; In this tutorial, you have learned how to create the image resize component for cropping and resizing the image size in react js application using the third party package called react image resize.

Recommended React JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *