React Image Upload with Crop and Zooming step by step

React-Image-Upload-with-Crop-and-Zooming

Implementing an image upload with crop and zooming in React can be achieved using various libraries. Below is an example using the react-image-crop library along with ‘react-avatar-editor’. The ‘react-image-crop’ library is used for basic image cropping, and ‘react-avatar-editor’ is used for additional zooming functionality.

Step 1: Set Up Your React Project

If you haven’t created a React project yet, you can do so using Create React App:

npx create-react-app image-upload-crop
cd image-upload-crop

Step 2: Install Required Packages

Install the necessary packages using:

npm install react-image-crop react-avatar-editor

Step 3: Create ImageUploadCrop Component

Create a new React component named ‘ImageUploadCrop.js’ for handling image upload, crop, and zoom:

// src/components/ImageUploadCrop.js

import React, { useState } from 'react';
import ReactCrop from 'react-image-crop';
import AvatarEditor from 'react-avatar-editor';
import 'react-image-crop/dist/ReactCrop.css';

const ImageUploadCrop = () => {
  const [image, setImage] = useState(null);
  const [crop, setCrop] = useState({ aspect: 1 / 1 });
  const [editor, setEditor] = useState(null);

  const onFileChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedImage = e.target.files[0];
      setImage(URL.createObjectURL(selectedImage));
    }
  };

  const onCropChange = (crop) => {
    setCrop(crop);
  };

  const handleZoomChange = (e) => {
    setEditor(e);
  };

  const handleCrop = () => {
    if (editor) {
      const canvasScaled = editor.getImageScaledToCanvas();
      const croppedImage = editor.getImageScaledToCanvas().toDataURL();
      // Handle the cropped image as needed
      console.log('Cropped Image:', croppedImage);
    }
  };

  return (
    
{image && (

Zoom: handleZoomChange(e.target.value)} min="1" max="3" step="0.01" defaultValue="1" />

setEditor(editor)} image={image} width={250} height={250} border={50} color={[255, 255, 255, 0.6]} // RGBA scale={1 + parseFloat(editor)} rotate={0} />
)}
); }; export default ImageUploadCrop;

Step 4: Use ImageUploadCrop in App.js

Include the ImageUploadCrop component in your src/App.js file:

// src/App.js

import React from 'react';
import ImageUploadCrop from './components/ImageUploadCrop';

function App() {
  return (
    

Image Upload with Crop and Zoom

); } export default App;

Step 5: Run Your React App

Save your files and run:

npm start

Visit http://localhost:3000 in your browser to see and test the image upload with crop and zoom functionality.

Note: You may need to handle styling, error checking, and other aspects based on your specific requirements. Additionally, you might want to consider other libraries or tools for image manipulation based on your project needs.

Related Posts