How To Resize an Image in React

Quickly resize an image with the `react-image-file-resizer` React library.


6 min read
How To Resize an Image in React

In this article, you will see how to resize an image in JavaScript. In particular, here you will learn to achieve this goal with the react-image-file-resizer React library. If you are looking for a pure Javascript solution, here's a quick rundown of the HTML API usage.

Providing users with features to resize images has become almost unavoidable. This is because images are larger than ever. It is not a secret that the quality of the images and therefore their file sizes have been increasing for years.

The problem is that dealing with large files is time-consuming. Plus, it may cost money in bandwidth when uploading or downloading them. This is why it is so important to shrink the size of images by resizing them. Also, these issues fall on end-users, and this should be avoided.

So, let’s see how to resize an image in React with react-image-file-resizer. By following this step-by-step tutorial, you will achieve the following result:

Prerequisites

This is the list of all the prerequisites for the demo application you are going to build:

Resizing an Image with react-image-file-resizer

You can clone the GitHub repository that supports this article and try the demo application by launching the following commands:

git clone https://github.com/Tonel/resize-image-react-demo-imgly
cd resize-image-react-demo-imgly
npm i
npm start

Otherwise, you can continue following this tutorial and build the demo application step by step.

1. Creating a React Project

Generate an empty working project in React with Create React App, the officially supported way to create single-page React applications. You can initialize a new project called react-image-resizer-demo with the following command:

npx create-react-app react-image-resizer-demo

You will now have a demo project located in the react-image-resizer-demo folder with the following file structure:

react-image-resizer-demo
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    ├── reportWebVitals.js
    └── setupTests.js

Move into the react-image-resizer-demo folder and start a local server by launching these commands:

cd react-image-resizer-demo
npm start

Reach http://localhost:3000/ in your browser. You should now be able to see the default Create React App screen, as follows:

The default Create React App screen

2. Installing react-image-file-resizer

First, you have to add the react-image-file-resizer library to your project’s dependencies. You can do it by running the following command:

npm install --save react-image-file-resizer

Thus, your package.json file will be updated accordingly. You should now be able to spot react-image-file-resizer as a dependency.

Now, all prerequisites have been met. So, you can start building your image resizer component. Let’s see together how.

3. Building the Image Resizer Component

First, make a components folder inside src. Then, create an ImageResizer folder containing index.js and index.css. These two files will contain the resizer component definition and style respectively.

The components folder

Initialize index.js with the following snippet:

import React from "react";

function ImageResizer() {
    return (
        <div>
            {/*TODO*/}
        </div>
    );
}

export default ImageResizer;

This way, you have just defined an empty ImageResizer component.
Now, import the Resizer utility from the react-image-file-resizer library. Add it to the ImageResizer imports:

import Resizer from 'react-image-file-resizer'

This is what the final ImageResizer will look like:

import React, {useEffect, useState} from "react";
import Resizer from "react-image-file-resizer";

function ImageResize(props) {
    const {imageToResize, onImageResized, resizeAspect, resizeQuality} = props;

    const [imageToResizeUri, setImageToResizeUri] = useState();
    const [imageToResizeWidth, setImageToResizeWidth] = useState();
    const [imageToResizeHeight, setImageToResizeHeight] = useState();

    useEffect(() => {
        if (imageToResize) {
            const reader = new FileReader();

            reader.addEventListener('load', () => {
                setImageToResizeUri(reader.result);
            });

            reader.readAsDataURL(imageToResize);
        }
    }, [imageToResize])

    useEffect(() => {
        if (imageToResize && imageToResizeWidth && imageToResizeHeight) {
            Resizer.imageFileResizer(
                imageToResize,
                imageToResizeWidth * resizeAspect,
                imageToResizeWidth * resizeAspect,
                "JPEG",
                resizeQuality,
                0,
                (uri) => {
                    onImageResized(uri)
                },
                "base64"
            );
        }
    }, [
        imageToResize, imageToResizeWidth, imageToResizeHeight,
        onImageResized, resizeAspect, resizeQuality
    ]);

    return (
        <img
            src={imageToResizeUri}
            onLoad= {(e) => {
                const img = e.target;
                setImageToResizeWidth(img.width);
                setImageToResizeHeight(img.height);
            }}
            crossorigin="anonymous" // to avoid CORS-related problems
        />
    );
}

ImageResize.defaultProps = {
    onImageResized: () => {},
    resizeAspect: 0.5,
    resizeQuality: 100
}

export default ImageResize;

imageToResize is the source Blob representing the image received from the props. First, imageToResize is transformed into a Base64 URI by the first useEffect() function, and then showed. After being loaded by the <img> HTML tag, the image’s width and height are saved to be used during the resizing operation. This is done by the second useEffect() function, which takes care of resizing the Blob image received by employing the Resizer utility.

Please, note that resizeAspect and resizeQuality are two props in charge of defining the resize aspect and quality percentage, respectively. By default, they are assigned to 0.5 and 100. This means that the resized image will be 50% smaller and no compression will be applied during the resizing process.

4. Putting It All Together

Now, let’s see the ImageResizer component defined above in action. All you need to do, is change the App.js file as follows:

import React, {useState} from "react";
import './App.css';
import ImageResize from "./components/ImageResizer";

function App() {
    const [imageToResize, setImageToResize] = useState(undefined);
    const [resizedImage, setResizedImage] = useState(undefined);

    const onUploadFile = (event) => {
        if (event.target.files && event.target.files.length > 0) {
            setImageToResize(event.target.files[0]);
        }
    };

    return (
        <div className="app">
            <h1>Image Resizer</h1>
            <p>
                Please, upload an image and it will be showed both original and resized by
                50%
            </p>
            <input
                type="file"
                accept="image/*"
                onChange={onUploadFile}
            />
            <div>
                <ImageResize
                    imageToResize={imageToResize}
                    onImageResized={(resizedImage) => setResizedImage(resizedImage)}
                />
            </div>
            {
                resizedImage &&
                <div>
                    <h2>Resized Image</h2>
                    <img
                        alt="Resize Image"
                        src={resizedImage}
                    />
                </div>
            }
        </div>
    );
}

export default App;

The input element allows users to upload an image. This is stored in the imageToResize state variable, and then passed to ImageResizer as a props. This will take care of resizing it accordingly. The resulting resized image is saved thanks to the setResizedImage function, and finally displayed in the Resize Image section.

If you are a Next.js user, you can use the <Image /> component to make it resize images for you. React will then render resized images automatically.

Final Considerations on react-image-file-resizer

Resizing an image cannot be considered a complex task. However, using a library like react-image-file-resizer makes everything easier. In fact, you can achieve your goal with just a handful of lines of code. On the other hand, you should take into account what using such specific libraries implies. In fact, when you need to perform many image-related operations, you may be ending up with as many libraries as operations required.

Not only might they be complex to make them coexist, but they may have very different UIs as well. This is why, harnessing a commercial and more complete solution such as PhotoEditorSDK could be a better approach. With only one library, you would get several tools to deal with images as you need. This, while preserving the consistency of your application's UI. Plus, whenever you need help, you can ask for support from the img.ly developers who built the SDK.

Resizing an Image with PhotoEditorSDK

First, you should read this article from the official documentation on how to get started with PhotoEditorSDK in React. Then, by using the transform tool you can perform cropping, resizing, flipping, and rotation operations with just one feature. This way, you should be able to achieve the desired result

resize-image-with-pesdk-react

Conclusion

In this article, we looked at how to resize an image in React. Although this cannot be considered a complex feature to implement, using a library such as react-image-file-resizer is recommended. As we have seen, you can resize an image effortlessly and with only a few lines of code. On the other hand, it is a library with a very specific and limited purpose. So, if you needed to perform more than one operation on your images, you might want to take advantage of a more advanced and complete solution – such as PhotoEditorSDK.

Related Articles

CE.SDK v1.20 Release Notes
2 min read
CE.SDK v1.19 Release Notes
3 min read
CE.SDK v1.17 Release Notes
2 min read
CE.SDK v1.16 Release Notes
1 min read
CE.SDK v1.14 Release Notes
2 min read

GO TOP