<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeevanandham D on Medium]]></title>
        <description><![CDATA[Stories by Jeevanandham D on Medium]]></description>
        <link>https://medium.com/@djeevanandham553?source=rss-13d6c230cbfd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PXl2i7ca6Mwbq8Lr</url>
            <title>Stories by Jeevanandham D on Medium</title>
            <link>https://medium.com/@djeevanandham553?source=rss-13d6c230cbfd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:04:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@djeevanandham553/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Image Cropping & Rotation in React with react-image-crop(.jsx)]]></title>
            <link>https://medium.com/@djeevanandham553/image-cropping-rotation-in-react-with-react-image-crop-jsx-f2275fcd90bd?source=rss-13d6c230cbfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2275fcd90bd</guid>
            <category><![CDATA[image-cropping]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[react-image-crop]]></category>
            <category><![CDATA[canvas]]></category>
            <dc:creator><![CDATA[Jeevanandham D]]></dc:creator>
            <pubDate>Tue, 27 May 2025 11:06:11 GMT</pubDate>
            <atom:updated>2025-05-27T11:06:11.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQV1yztadgW-YOJ--V8g4g.jpeg" /><figcaption>source: Unsplash.com</figcaption></figure><p>In this tutorial, we will dive into how to implement <strong>image cropping</strong> and <strong>rotation</strong> in a <strong>React app</strong> using the popular library react-image-crop. Along the way, we&#39;ll cover some essential topics such as <strong>state management</strong>, <strong>image manipulation</strong>, and <strong>canvas rendering</strong> for seamless cropping and rotation.</p><p>Why Use react-image-crop?<br>react-image-crop is a powerful React component that allows users to crop images easily and precisely. It provides essential features like <strong>aspect ratios</strong>, <strong>aspect locking</strong>, and <strong>grid guidelines</strong> for better control over cropping. When combined with rotation functionality, it becomes even more powerful.</p><p>In this tutorial, we’ll implement the following features:</p><ol><li><strong>Image Cropping</strong>: Crop images dynamically using react-image-crop.</li><li><strong>Image Rotation</strong>: Rotate the image based on user input.</li><li><strong>Dynamic Image Preview</strong>: Show a cropped and rotated preview of the image.</li></ol><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Setting Up the Project<br>1. Install Dependencies</p><p>To get started, let’s first install the necessary dependencies:</p><pre>npx create-react-app react-image-crop-rotate<br>cd react-image-crop-rotate<br>npm install react-image-crop antd</pre><ul><li><strong>react-image-crop</strong>: The library for cropping images.</li><li><strong>antd</strong>: For UI components like buttons and loaders.<br>In addition, make sure to import the necessary styles for react-image-crop:</li></ul><pre>import &quot;react-image-crop/dist/ReactCrop.css&quot;;</pre><p>Now that we have the necessary setup, let’s move on to React-image-crop component.</p><p>2. <strong>Create Your React Component</strong></p><p>We’ll create a component that handles the cropping and rotation logic. Here’s how it will look: [App.jsx]</p><pre>import React, { useEffect, useState, useRef } from &quot;react&quot;;<br>import &quot;./styles.css&quot;;<br>import ReactCrop, { centerCrop, makeAspectCrop } from &quot;react-image-crop&quot;;<br>import demoImage from &quot;./assets/Demo.jpg&quot;;<br>import &quot;react-image-crop/dist/ReactCrop.css&quot;;<br>import useRotateImage from &quot;./customHooks/useRotate&quot;;<br>import { Button } from &quot;antd&quot;;<br>import { LoadingOutlined } from &quot;@ant-design/icons&quot;;<br>import { Flex, Spin } from &quot;antd&quot;;<br><br>export default function App() {<br>  const [gridAspectRatio, setGridAspectRatio] = useState(1);<br>  const [isImageLoading, setIsImageLoading] = useState(true);<br>  const [crop, setCrop] = useState({<br>    unit: &quot;%&quot;,<br>    width: 100,<br>    height: 100,<br>    x: 0,<br>    y: 0,<br>  });<br>  const [rotateDeg, setRotateDeg] = useState(0);<br>  const [imageDims, setImageDims] = useState({<br>    naturalWidth: 0,<br>    naturalHeight: 0,<br>    renderedWidth: 0,<br>    renderedHeight: 0,<br>  });<br>  const [completedCrop, setCompletedCrop] = useState(null);<br><br>  const rotatedImage = useRotateImage(demoImage, rotateDeg);<br>  const imageSrc = rotatedImage?.src || demoImage;<br><br>  //important based on requirement<br>  useEffect(() =&gt; {<br>    setGridAspectRatio(1);<br>    const updatedCrop = centerCrop(<br>      makeAspectCrop(<br>        {<br>          // You don&#39;t need to pass a complete crop into<br>          // makeAspectCrop or centerCrop.<br>          unit: &quot;%&quot;,<br>          width: 100,<br>        },<br>        1,<br>        imageDims.naturalWidth,<br>        imageDims.naturalHeight<br>      ),<br>      imageDims.renderedWidth,<br>      imageDims.renderedHeight // this param ensures crop within its width &amp; height<br>    );<br>    setCrop(updatedCrop);<br>  }, [rotateDeg]);<br><br>  const onImageLoad = (e) =&gt; {<br>    const img = e.currentTarget;<br>    setImageDims({<br>      naturalWidth: img.naturalWidth,<br>      naturalHeight: img.naturalHeight,<br>      renderedWidth: img.offsetWidth,<br>      renderedHeight: img.offsetHeight,<br>    });<br>    setGridAspectRatio(1); // not allowing user to free crop<br>    setIsImageLoading(false);<br>  };<br><br>  const imageResize = () =&gt; {<br>    let ratio = 0;<br>    // const maxWidth = 1040;<br>    // const maxHeight = 603;<br>    const maxWidth = 350;<br>    const maxHeight = 350;<br>    // const maxHeight = 540;<br><br>    const width = imageDims.renderedWidth;<br>    const height = imageDims.renderedHeight;<br><br>    let returnWidth;<br>    let returnHeight;<br>    let objectFit = &quot;contain&quot;;<br>    ratio = width / height;<br>    if (width &gt; maxWidth &amp;&amp; width &gt; height) {<br>      returnWidth = maxWidth;<br>      returnHeight = maxHeight;<br>      objectFit = &quot;cover&quot;;<br>    } else if (height &gt; maxHeight &amp;&amp; height &gt; width) {<br>      ratio = height / width;<br>      returnWidth = maxHeight / ratio;<br>      returnHeight = maxHeight;<br>    } else {<br>      returnWidth = maxHeight * ratio;<br>      returnHeight = maxHeight;<br>    }<br>    return { returnHeight, returnWidth, objectFit };<br>  };<br><br>  const imageStyles = imageResize();<br><br>  const handleCropChange = (pixelCrop, percentCrop) =&gt; {<br>    setCrop(pixelCrop);<br>  };<br><br>  const onCropComplete = (_, completeCropInPercentage) =&gt; {<br>    if (completeCropInPercentage.width &amp;&amp; completeCropInPercentage.height) {<br>      const updatedCropObj = {<br>        ...completeCropInPercentage,<br>      };<br>      setCompletedCrop(updatedCropObj);<br>    }<br>  };<br><br>  //cropped section i.e output section of crop<br>  const [croppedUrl, setCroppedUrl] = useState(null);<br>  const imgRef = useRef(null);<br><br>  const cropImage = () =&gt; {<br>    const image = new Image();<br>    image.crossOrigin = &quot;anonymous&quot;;<br>    image.src = imageSrc;<br><br>    image.onload = () =&gt; {<br>      const naturalWidth = image.naturalWidth;<br>      const naturalHeight = image.naturalHeight;<br><br>      const pixelCrop = {<br>        x: (completedCrop.x / 100) * naturalWidth,<br>        y: (completedCrop.y / 100) * naturalHeight,<br>        width: (completedCrop.width / 100) * naturalWidth,<br>        height: (completedCrop.height / 100) * naturalHeight,<br>      };<br><br>      const canvas = document.createElement(&quot;canvas&quot;);<br>      canvas.width = pixelCrop.width;<br>      canvas.height = pixelCrop.height;<br>      const ctx = canvas.getContext(&quot;2d&quot;);<br><br>      ctx.drawImage(<br>        image,<br>        pixelCrop.x,<br>        pixelCrop.y,<br>        pixelCrop.width,<br>        pixelCrop.height,<br>        0,<br>        0,<br>        pixelCrop.width,<br>        pixelCrop.height<br>      );<br><br>      const croppedImageUrl = canvas.toDataURL(&quot;image/png&quot;);<br>      setCroppedUrl(croppedImageUrl);<br>      setIsImageLoading(false);<br>    };<br><br>    image.onerror = () =&gt; {<br>      console.error(&quot;Failed to load image for cropping.&quot;);<br>    };<br>  };<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;Hello Guys&lt;/h1&gt;<br>      &lt;h2&gt;React-image-crop&lt;/h2&gt;<br>      &lt;h2&gt; Drag your cursor on image to magic happen!&lt;/h2&gt;<br>      &lt;div className={&quot;reactCropContainer&quot;}&gt;<br>        &lt;ReactCrop<br>          aspect={gridAspectRatio}<br>          crop={crop}<br>          onChange={handleCropChange}<br>          ruleOfThirds={true}<br>          minWidth={100}<br>          minHeight={100}<br>          style={{<br>            maxWidth:<br>              imageStyles.returnWidth &gt; 0 || imageDims.renderedWidth &gt; 0<br>                ? `${imageStyles.returnWidth || imageDims.renderedWidth}px`<br>                : &quot;100%&quot;,<br>            maxHeight: `${<br>              imageStyles.returnHeight || imageDims.renderedHeight<br>            }px`,<br>          }}<br>          onComplete={onCropComplete}<br>        &gt;<br>          &lt;img<br>            src={imageSrc}<br>            onLoad={onImageLoad}<br>            className={&quot;reactCropImage&quot;}<br>          /&gt;<br>        &lt;/ReactCrop&gt;<br>        {isImageLoading &amp;&amp; (<br>          &lt;div<br>            style={{<br>              position: &quot;absolute&quot;,<br>              alignItems: &quot;center&quot;,<br>              // width: &quot;100%&quot;,<br>              // height: &quot;100%&quot;,<br>              display: &quot;flex&quot;,<br>              alignContent: &quot;center&quot;,<br>            }}<br>          &gt;<br>            &lt;Spin<br>              indicator={&lt;LoadingOutlined style={{ fontSize: 48 }} spin /&gt;}<br>            /&gt;<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>      &lt;div style={{ display: &quot;flex&quot;, gap: &quot;1rem&quot; }}&gt;<br>        &lt;Button<br>          onClick={() =&gt; {<br>            setIsImageLoading(true);<br>            setRotateDeg((r) =&gt; (r + 90) % 360);<br>          }}<br>          disabled={isImageLoading}<br>        &gt;<br>          Rotate Left<br>        &lt;/Button&gt;<br>        &lt;Button<br>          onClick={() =&gt; {<br>            setIsImageLoading(true);<br>            setRotateDeg((r) =&gt; (r - 90) % 360);<br>          }}<br>          disabled={isImageLoading}<br>        &gt;<br>          Rotate Right<br>        &lt;/Button&gt;<br>        &lt;Button<br>          onClick={() =&gt; {<br>            setIsImageLoading(true);<br>            cropImage();<br>          }}<br>          disabled={isImageLoading}<br>        &gt;<br>          Crop Image<br>        &lt;/Button&gt;<br>      &lt;/div&gt;<br>      &lt;div style={{ marginTop: 20 }}&gt;<br>        &lt;h3&gt;Cropped Image:&lt;/h3&gt;<br>        &lt;img<br>          crossOrigin=&quot;anonymous&quot;<br>          ref={imgRef}<br>          src={croppedUrl || demoImage}<br>          alt=&quot;Cropped&quot;<br>          className=&quot;reactCropContainer&quot;<br>          style={{ width: &quot;100px&quot;, height: &quot;100px&quot; }}<br>        /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>//points to remember<br>// 1.adjust gridAspectRatio to cut the image across the flow<br>//for freestyle remove prop</pre><h3>Image Rotation with React</h3><p>Image rotation is an essential feature when you’re working with image manipulation. Here’s how you can implement a simple image rotation feature in React.</p><p>We’ll create a custom hook called useRotateImage that handles the image rotation logic. This will allow us to rotate an image based on the degree we pass as a parameter.</p><h3>useRotateImage Hook</h3><pre>import { useEffect, useRef, useState } from &quot;react&quot;;<br><br>let canvas = null;<br>let canvasCtx2D = null;<br><br>const getRotatedImage = (image, rotation) =&gt; {<br>  canvas ??= document.createElement(&quot;canvas&quot;);<br>  canvasCtx2D ??= canvas.getContext(&quot;2d&quot;);<br><br>  if (!image || !canvasCtx2D) return null;<br><br>  const { width: imageWidth, height: imageHeight, currentSrc } = image;<br>  const degree = -(rotation % 360);<br>  if (!degree) {<br>    return {<br>      src: currentSrc,<br>      width: imageWidth,<br>      height: imageHeight,<br>    };<br>  }<br><br>  const { PI, sin, cos, abs } = Math;<br>  const angle = (degree * PI) / 180;<br>  const sinAngle = sin(angle);<br>  const cosAngle = cos(angle);<br><br>  canvas.width = abs(imageWidth * cosAngle) + abs(imageHeight * sinAngle);<br>  canvas.height = abs(imageWidth * sinAngle) + abs(imageHeight * cosAngle);<br><br>  // The width and height of the canvas will be automatically rounded.<br>  const { width: canvasWidth, height: canvasHeight } = canvas;<br><br>  canvasCtx2D.clearRect(0, 0, canvasWidth, canvasHeight);<br>  canvasCtx2D.translate(canvasWidth / 2, canvasHeight / 2);<br>  canvasCtx2D.rotate(angle);<br><br>  canvasCtx2D.drawImage(<br>    image,<br>    -imageWidth / 2,<br>    -imageHeight / 2,<br>    imageWidth,<br>    imageHeight<br>  );<br><br>  const src = canvas.toDataURL(&quot;image/png&quot;);<br>  canvas.width = 0;<br>  canvas.height = 0;<br>  return {<br>    src,<br>    width: canvasWidth,<br>    height: canvasHeight,<br>  };<br>};<br><br>const useRotateImage = (imageSrc, rotation) =&gt; {<br>  const imageEle = useRef(null);<br>  const [rotatedImage, setRotatedImage] = useState(null);<br><br>  useEffect(() =&gt; {<br>    if (typeof rotation === &quot;number&quot;) {<br>      let currImage = imageEle.current;<br><br>      if (currImage?.currentSrc !== imageSrc) {<br>        currImage = new Image();<br>        currImage.crossOrigin = &quot;anonymous&quot;;<br>        imageEle.current = currImage;<br><br>        currImage.src = imageSrc;<br>      }<br><br>      currImage.decode().then(<br>        () =&gt; setRotatedImage(getRotatedImage(currImage, rotation)),<br>        () =&gt; setRotatedImage(null)<br>      );<br>    }<br>  }, [imageSrc, rotation]);<br><br>  return rotatedImage;<br>};<br><br>export default useRotateImage;</pre><p>Now that we have rotation working, it’s time to put in action.</p><h3>Conclusion</h3><p>In this article, we’ve covered how to integrate <strong>image cropping</strong> and <strong>rotation</strong> functionality into a React application. Using a combination of <strong>custom hooks</strong> and <strong>third-party libraries</strong> like react-image-crop, we were able to create a feature-rich image editor with minimal effort.</p><p>Here’s a summary of what we’ve done:</p><ul><li>Integrated <strong>react-image-crop</strong> to handle image cropping.</li><li>Managed image loading, rotation, and cropping within a functional React component.</li><li>Implemented <strong>image rotation</strong> using canvas and React hooks.</li></ul><p>Now, you can easily integrate these techniques into your projects to allow users to manipulate images in a clean and intuitive way.</p><h3>Live Demo on CodeSandbox</h3><p>I’ve built a working version of this project that you can interact with directly in your browser. Try out the cropping and rotation features for yourself by visiting the live demo below:</p><p><a href="https://codesandbox.io/p/sandbox/2tfygx"><strong>Live Demo on CodeSandbox</strong></a></p><p>Feel free to play around with the code, make edits, and see the result in real-time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2275fcd90bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>