Web development basic and advance tutorial, php basic tutorial, laravel basic tutorial, React Native tutorial

Monday, November 28, 2022

React JS Image upload and Crop

0 comments

React JS Image upload and Crop


Today, I will teach You How to crop an Image in React Js using 
the react-image-crop Package. Image Crop in React JS.

I will show you How to crop an Image and Download the Image 
to You Local Computer. So First I will choose the File then Try to crop it.

Step 1: Create React Project
Step 2: Install React Image Crop Library
Step 3: Build Image Crop Component


step 1 :
Create React Project

First step is to install the new React application with the given command.

npx create-react-app reactcropimage

Move into the app folder.

cd reactcropimage

step 2 :
        Install React Image Crop Library

        Secondly, you have to install the react-image-crop library, you may use the given command.

        npm install react-image-crop

step 3 :
        Build Image Crop Component
        npm i react-responsive-modal // install this library for Modal Popup div

Now we will create js page it will be name : Uploadpage.js

import React, { useState } from 'react'; import { Modal } from 'react-responsive-modal'; import { Button } from 'reactstrap'; import ReactCrop from 'react-image-crop' // crop image import 'react-image-crop/dist/ReactCrop.css'// crop image css import { render } from "react-dom"; import "react-responsive-modal/styles.css"; const styles = { fontFamily: "sans-serif", textAlign: "center" }; const Uploadpage =() => { return ( ) } export default Uploadpage;


Now create modal popup div <Modal open={open} onClose={onCloseModal} center> <h2>Image Upload</h2> </Modal>


now i am going to add button to open popup div

 <Button onClick={onOpenModal}>Open modal</Button>




const [open, setOpen] = useState(false);

  const onOpenModal = () => setOpen(true);
  const onCloseModal = () => setOpen(false);

when user will click on button it will open popup div and it will work on close as well as.

 <input type="file" accept='image/*' onChange={handlefilechange} />



when user will choose image it will handle the image

const handlefilechange = event => {
    const files = event.target.files
    if (files && files.length > 0){
             const currentFile = files[0]
             const myFileItemReader = new FileReader()
             myFileItemReader.addEventListener("load", ()=>{
                 const myResult = myFileItemReader.result
                 setImage(myResult)
             }, false)

             myFileItemReader.readAsDataURL(currentFile)
    }
}



here is the full complete code

import React, { useState } from 'react';

import { Modal } from 'react-responsive-modal';
import { Button } from 'reactstrap';
import ReactCrop from 'react-image-crop' // crop image
import 'react-image-crop/dist/ReactCrop.css'// crop image css
import { render } from "react-dom";
import "react-responsive-modal/styles.css";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};


const Uploadpage =() => {
  const [open, setOpen] = useState(false);

  const onOpenModal = () => setOpen(true);
  const onCloseModal = () => setOpen(false);


  const [image, setImage] = useState(null);
  const [crop, setCrop] = useState({
    unit: "%",
    x: 0,
    y: 0,
    width: 150,
    height: 150
  })
  const [imagedetails, setImagedetails] = useState('')
  const [croppedImageUrl, setCroppedImageUrl] = useState("");

 
const handlefilechange = event => {
    const files = event.target.files
    if (files && files.length > 0){
             const currentFile = files[0]
             const myFileItemReader = new FileReader()
             myFileItemReader.addEventListener("load", ()=>{
                 const myResult = myFileItemReader.result
                 setImage(myResult)
             }, false)

             myFileItemReader.readAsDataURL(currentFile)
    }
}

const saveimage= () => {
  const canvas = document.createElement("canvas");
  canvas.width = imagedetails.naturalWidth;
      canvas.height = crop.naturalHeight;
      const ctx = canvas.getContext("2d");
      ctx.translate(canvas.width /2, canvas.height / 2)
      ctx.drawImage(
        imagedetails,
        -canvas.width / 2,
        -canvas.height / 2,
        canvas.width,
        canvas.height
      )
      const link = document.createElement('a')
      link.download = "p.jpg";
      link.href = canvas.toDataURL();
      link.click();
}
   const getCroppedImg = () => {

      const canvas = document.createElement("canvas");
      const scaleX = imagedetails.naturalWidth / imagedetails.width;
      const scaleY = imagedetails.naturalHeight / imagedetails.height;
      canvas.width = crop.width;
      canvas.height = crop.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(
      imagedetails,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
      );
      const base64Url = canvas.toDataURL('image/jpg')
      setImage(base64Url)


    /*
    try {
      return new Promise((resolve) => {
        canvas.toBlob((file) => {
          resolve(URL.createObjectURL(file));
        }, "image/jpeg");
      });
    } catch (error) {
      console.log(error);
      return null;
    } */
  };

  const handlecropchange=(crop) => {
    setCrop(crop)
  }
console.log('monir' + imagedetails)
  return (
   
    <div style={styles}>
      <Button onClick={onOpenModal}>Open modal</Button>
      <Modal open={open} onClose={onCloseModal} center>
        <h2>Image Upload</h2>
        <input type="file" accept='image/*' onChange={handlefilechange} />
          <p>
     
       {/*  <ReactCrop crop={crop} onChange={setCrop}>
        <img src={src} />
        </ReactCrop> */}
        {
          image == null ?
          ''
          :
          <div>
             <ReactCrop crop={crop} onChange={c => setCrop(c)}>
              <img onLoad={(e) => setImagedetails(e.currentTarget)}  src={image} />
            </ReactCrop>
          </div>
        }

        </p>
          {
            image && <div><Button onClick={getCroppedImg}>Crop Image </Button> <Button onClick={saveimage}>Save </Button></div>
          }
           </Modal>
    </div>
   
  );
}

export default Uploadpage;
                       Last Output



No comments:

Post a Comment