Guides
Last updated
August 2, 2023

How to Resize an Image in React

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Image resizing is crucial to any frontend web app or mobile app. Image files are larger than ever, and users expect a lightning-fast web browsing experience. Serving optimized images decreases load times and makes your site or app snappy and responsive. Reducing file sizes for upload decreases upload times and makes for a smoother user experience.

These days, there are many ways to implement image resizing in React. Plenty of libraries exist for this purpose, including react-image-file-resizer and browser-image-compression. With the prevalence of serverless architecture, low-code and no-code operations, and API-based solutions, image-resizing APIs have also become very popular.

In this tutorial, we’ll learn how to create rescaled local images in a frontend React app. We’ll look at two different methods: using react-image-file-resizer, and using the AbstractAPI Image Processing API. This article won’t go in-depth into how to build a basic React app. If you need help getting started with React, we suggest reading the docs or checking out this tutorial.

Let’s send your first free
call
See why the best developers build on Abstract
Get your free api

Resize an Image Using React Image File Resizer

React image file resizer is a React module that allows you to rescale and resize images from the device’s file system. It does basic resizing and compression, including adjusting the image’s width, height, quality, rotation, and format. Images are returned as a base64 URI or Blob.

Getting Started With React Image File Resizer

To install the module, use NPM or Yarn.



npm install -s react-image-file-resizer



yarn add react-image-file-resizer

You can then import the module into you app js file or wherever you need it, and use it as follows



Resizer.imageFileResizer(
file,
maxWidth,
maxHeight,
compressFormat,
quality,
rotation,
responseUriFunc,
outputType,
minWidth
minHeight
);

The file, maxWidth, maxHeight, compressFormat, quality, rotation and responseUriFunc arguments are all required. The rest are optional

Resize Images Using the Library

Pass the URI to the file you wish to resize as the file argument, pass the desired height, width, rotation, and quality parameters, and pass a callback function to the responseUriFunc argument.

The callback function will receive the URI to the new image file as an argument. From there, you can do what you need to do with it.

One possible implementation might look like this:



import Resizer from "react-image-file-resizer";

const callback = (newFileUri) => this.setState({resizedImage: newFileUri});

const resizeImage = (imageFile) => {
try {
Resizer.imageFileResizer(
imageFile,
150,
150,
"JPEG",
100,
0,
callback,
);
} catch (err) {
console.log(err);
}
}

const handleImageResize = (event) => resizeImage(event.target.files[0]);

Compressing Files

To compress a file using the library, simply pass a lower quality option and leave the height and width options as they are in the original file. You can use the image metadata to find out what the original width and height of the image are, then pass those to the function.



const resizeImage = (imageFile) => {
const height = imageFile.height;
const width = imageFile.width;
try {
Resizer.imageFileResizer(
imageFile,
height,
width,
"JPEG",
75,
0,
callback,
);
} catch (err) {
console.log(err);
}
}

Here, we’ve lowered the image quality to 75% but left the size of the image alone. This will cause lossy compression to be performed on the file, reducing the file’s size and causing a small reduction in image quality.

Resize an Image Using AbstractAPI

The AbstractAPI Image Processing API provides a secure REST endpoint where you can compress, convert, resize, and crop your images. There are two methods for working with an image file in the API: direct upload through multipart form data, or a POST request with the URL for a hosted image contained in the request options. The API returns resized image's URL at a hosted endpoint.

In this tutorial, we’ll use a hosted image:

https://s3.amazonaws.com/static.abstractapi.com/test-images/dog.jpg

Acquire an API Key

To gain access to the secure API, you’ll need an API key. Navigate to the Image API homepage and click “Get Started.”

You may need to create a free account by providing an email address and a password. If you’ve used AbstractAPI before, you may need to log in. Once you’ve logged in, you’ll land on the API dashboard.

The dashboard displays links to documentation and pricing, settings and usage reports, as well as your API key. The API is free to use for up to 100MB per month.

Resize Images Using the API

Resizing an image using the API is as simple as sending a POST request with some options parameters. To make the request from your React app, the code might look something like this:



const sendResizeImageRequest = async () => {
const requestOptions = { method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ api_key: 'YOUR_API_KEY,
url: ‘https://s3.amazonaws.com/static.abstractapi.com/test-images/dog.jpg’,
resize: { ‘width’: 100, strategy: ‘auto’ }
' }) };
onst response = await fetch('https://reqres.in/api/posts', requestOptions);
const data = await response.json();
console.log(data);
}

When you log the data object to the console, you’ll see the following:



{
"original_size": "the size of the original input image, in bytes",
"original_height": "original height in pixels of the image",
"original_width": "original width in pixels of the image",
"final_size": "the size of the new image, in bytes",
"bytes_saved": "the number of bytes saved by compressing and resizing the image",
"final_height": "final height in pixels of the image",
"final_width": "final width in pixels of the image",
"url": "url of the image hosted by Abstract API for you to download. Images are available for 1 day.",
}

By setting the resize options to change image's width and using the auto strategy, we told the API to resize the image to the specified width and maintain the aspect ratio. You could also use the exact strategy to resize the image to an exact height and width, without maintaining the aspect ratio, or use the fit strategy to crop the image to fit into a given width and height.

Compress an Image Using the API

You can also pass a lossy option to tell the API to use lossy compression to compress the file size. When omitted, this option defaults to false, so image quality will not be affected, however, file size  will still shrink slightly (about 10-20%.)

Let’s use lossy image compression to compress the image using the endpoint. Update the request from the previous example to request image compression instead of resizing.



const sendCompressImageRequest = async () => {
const requestOptions = { method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ api_key: 'YOUR_API_KEY,
url: ‘https://s3.amazonaws.com/static.abstractapi.com/test-images/dog.jpg’,
lossy: true,
quality: 75
' }) };
const response = await fetch('https://reqres.in/api/posts', requestOptions);
const data = await response.json();
console.log(data);
}

We set the lossy boolean to true and told the API to maintain an image quality of 75%. AbstractAPI recommends that you don’t mess with the quality option unless you’re sure you know how the output image will be affected. When the quality option is not provided, the API determines the quality output intelligently, so it’s generally best to let the API handle this.

Specifying a quality of more than 95 may result in a larger image than the original. Anything less than 25 could result in an unusably low-quality image.

When you log the output, you’ll see something like this:



{
"original_size":205559,
"original_height":430,
"original_width":1142,
"final_size":75101,
"bytes_saved":130458,
"final_height":430,
"final_width":1142,
"url":"https://abstractapi-images.s3.amazonaws.com/8f2dd6392c524bc98313a89a24012b1f_dog.jpg"
}

When you compare the original_width and final_width and original_height and final_height, you can see there has been no reduction in image size. However, there has been a decrease of about 130458 bytes in the size of the file.

Conclusion

Resizing images in React is important, but fortunately, also very easy. Using a library like react-image-file-resizer, or a dedicated third-party API like the AbstractAPI Image Processing and Optimization API makes it very easy to outsource your image resizing and processing.

FAQs

How Do I Resize an Image in ReactJS?

There are several ways to resize an image in React. You could use a library like react-image-crop or react-image-file-resizer. These packages expose numerous methods for working with images. They install quickly and don’t increase your bundle size too much.

If you’d rather not install any additional packages to your React app, you could use a third-party API like the AbstractAPI Image Processing and Optimization API. This API exposes an endpoint where you can upload image files and receive a response containing a URL to the newly resized, hosted image.

How Can I Fit an Image Into a Div in React?

The easiest way to fit an image into a div in React is to specify that the image’s width and height automatically assume the width and height of the parent div. You can do this by setting the CSS width and height properties on the image element to 100% and using the object-fit property.

The object-fit property tells the image how it should shrink, expand, crop, or otherwise fill the available space of the parent div. There are several options, including cover, fill, contain, scale-down, and none.

How Do I Change the Size of My Logo In React?

Changing the size of a logo is the same as changing the size of any other image in React. If you need to physically change the size of the image file itself, you can use a library like react-image-file resizer, or an API like the AbstractAPI Image Processing and Optimization API.

If you simply need to fit the logo into a div for display, adjust the image elements width and height, or adjust the width and height of the parent div. Read up on the object-fit property to learn how images are auto-scaled to fill available div space.

Elizabeth (Lizzie) Shipton

Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.

Get your free
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required