INTRODUCTION:
In this blog, I’ll explain about How to crop the images and preview the cropped Image
I used the npm cropperjs
For easy understanding, I start the application from starting.
Step 1:
From the command line, execute the following:
npx create-react-app image-crop-exampleThe above command will create a new project with the default template. The default template contains a little more code than we need, so let’s take a moment to clean it up.
Open the project’s src/App.js file and make it look like the following:
import React from ‘react’;
function App() {
return (
< div >
);
export default App;
React Image Crop and Preview
Step 2:
From the command line, we install the npm
npm install cropperjs –save
Step 3:
Now write the code as below, Custom component file
import React from “react”;
import Cropper from “cropperjs”;
import “cropperjs/dist/cropper.min.css”;
import “./imagecropper.css”;
class CroppedImage extends React.Component {
constructor() {
super();
this.state = {
croppedImg: “”
};
this.imageElement = React.createRef();
}
componentDidMount() {
const cropper = new Cropper(this.imageElement.current, {
zoomable: false,
scalable: false,
// aspectRatio: 1,
crop: () => {
const canvas = cropper.getCroppedCanvas();
new Promise((resolve, reject) => {
canvas.toBlob(blob => {
blob[‘preview’] = URL.createObjectURL(blob);
this.setState({ croppedImg: blob })
resolve(blob);
}, ‘image/jpeg’, 1);
})
this.setState({ croppedImg: canvas.toDataURL(“image/png”) });
}
});
}
render() {
return (
< div >
< div class=”img-container” >
< img ref={this.imageElement} src={this.props.selectedImage} alt=”Source” crossorigin / >
< /div >
< img src={this.state.croppedImg} class=”img-preview” alt=”Destination” / >
< /div >
);
}
}
export default CroppedImage;
React Image Crop and Preview
componentDidMount() {
const cropper = new Cropper(this.imageElement.current, {
zoomable: false,
scalable: false,
// aspectRatio: 1,
crop: () => {
const canvas = cropper.getCroppedCanvas();
new Promise((resolve, reject) => {
canvas.toBlob(blob => {
blob[‘preview’] = URL.createObjectURL(blob);
this.setState({ croppedImg: blob })
resolve(blob);
}, ‘image/jpeg’, 1);
})
this.setState({ croppedImg: canvas.toDataURL(“image/png”) });
}
});
}
In ComponentDidMount ,
this.imageElement.current refers to image which we crop ,
zoomable: is the Cropping portion zoomable,
scalable:is the Cropping portion scalable,
crop: Its to draw the new Cropped Image, in this, we assign all canvas data to the canvas which return a promise
In resolving the promise, we assign blob[‘preview’] to display cropped Img
URL.createobjectURL(blob), to create the local link to display
CSS File:
.img-container {
width: 640px;
height: 480px;
float: left;
}
.img-preview {
width: 200px;
height: 200px;
float: left;
margin-left: 10px;
}
Use the custom component as :
< ImageCrop
selectedImage={‘https://homepages.cae.wisc.edu/~ece533/images/monarch.png’}
/>