Guides
Last updated
August 2, 2023

How to Resize an Image using an API

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 quality has been improving in leaps and bounds over the last ten or twenty years. Smartphone cameras have given everyone the ability to take and share the kind of pictures that used to only be attainable through the use of expensive, specialized equipment. High-quality digital images are now as easy to come by as dropped pennies.


The upshot of this is that as image quality has increased, file size has also increased. Not only that, the prevalence of images in websites and applications is more ubiquitous than ever. Image compression and resizing allow a site to serve responsive images and resized images fast, and enable faster image uploads. 

Image Resizing Methods

There are many ways to transform images within code to get a high-quality resized image. Libraries like react-image-file-resizer are popular options for those working with React on the frontend. PIL is a popular Python image manipulation library, and jimp and sharp are two great options for working with images in Node.

In today’s world, though, serverless architecture is becoming more and more prevalent, and developers are turning to APIs to handle many of the backend tasks that they used to code themselves. AWS Lambda functions can be built to handle image compression, and a plethora of APIs exist specifically to handle image manipulation, resizing needs, and transform images in a multitude of other ways.

In this article, we’ll look at one such image resize API—the AbstractAPI Image Processing and Optimization API. We’ll learn how to get a resized image using the API without sacrificing image quality, and also how to compress an image using the API without changing the size.

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

Get Started With the API

The AbstractAPI Image Resize API allows you to compress, convert, resize, and crop your images through an easily accessible, API key-protected REST endpoint. The API allows two methods for working with an image: a direct file upload to the API through multipart form data, or a simple POST request containing the URL for a hosted image.

In this tutorial, we’ll work with an image already hosted in an AWS S3 bucket:

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

This is an image provided by AbstractAPI to use when testing the endpoint.

Acquire an API Key

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

If you’ve never used AbstractAPI before, you will need to create a free account using an email address and a password. Once you’ve logged in, you’ll land on the API dashboard.

The dashboard contains links to documentation and pricing, settings and usage reports, as well as your API key.

Resize an Image

First, let’s look at the process of resizing an image using the API. Because the API operates through a simple REST endpoint, it is language-agnostic. It’s not necessary to install an SDK or any other kind of library to interface with the endpoint. A POST request with the image URL is all that’s needed.

Let’s assume you’re sending your request from a React frontend as part of a serverless app such as a Gatsby site. The code you would use to send the request would look 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’ }
' }) };
const response = await fetch('https://reqres.in/api/posts', requestOptions);
const data = await response.json();
console.log(data);
}

When we log the data object, we will see something like 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.",
}

In this case, because we set the resize options to resize just the width and use the auto strategy, the image will be resized to the specified width and the aspect ratio will be maintained. Other options include the ability to resize the image to the exact height and width given, without maintaining the aspect ratio, or to crop the image to fit into a given width and height (through the exact, and fit strategies.)

The image quality will not be affected by this process. AbstractAPI provides a lossy option to specify whether you would like the API to use lossy compression to compress the file size. If the option is omitted, it defaults to false. When false, the image filesize will still be reduced a small amount (about 10-20%) but there will be no affect on the image quality.

Compress an Image

Let’s now take a look at simple lossy image compression using the AbstractAPI endpoint. Keep in mind that the API only provides the option for lossy image compression, so when compressing any image in this way, there will be some small decrease in the image quality.

Update the request method we built in the previous example to request image compression rather than 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);
}

Here, we’ve set the lossy boolean to true, and specified that we’d like to maintain an image quality of 75%. Generally, AbstractAPI recommends that you do not provide a quality option unless you know what you are doing. If the quality option is not provided, the API will determine the quality output intelligently. Specifying a quality of over 95 could result in a larger image than the original, while anything less than 25 will result in an unusably low-quality image.

When we log the data, we will see something like the following:



{
"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"
}

As you can see, there has been no reduction in image size (as evidenced by comparing the original_width and final_width and original_height and final_height.) There has, however, been a decrease in the size of the file, of about 130458 bytes.

Conclusion

Using APIs for image compression and manipulation is an excellent way to build low-code and no-code solutions for image processing apps. In this how-to-guide, we looked at using one such API—the AbstractAPI Image Processing and Optimization API—to both resize a hosted image and compress that image using lossy compression.

FAQs

How Do I Resize An Image In Code?

There are many ways to resize images in code, and the method you choose will depend on the language you are using, and what the resulting image will be used for. If you are simply resizing a loaded image for display, setting the height and width attributes via CSS or HTML may be enough.

If you need to resize an image for upload, using a library like react-image-file-resizer, or an API like AbstractAPI’s Image Processing API are excellent solutions. If you need to resize an image on the backend, APIs also work, or there are many image processing libraries available for various languages.

What Is An Image API?

In programming, API stands for “Application Programming Interface” and it refers to any library or hosted solution that helps a developer complete a task in code. Usually, an API is a remote endpoint that you access through some kind of network request, send your data along for manipulation, and receive a response.

An image API is an API that receives requests with image data, and performs some kind of operation on that data (for example, resizing, compressing, cropping, filtering, etc.) and then returns either the new image file, or a link to the new image hosted somewhere.

What Is the HTML Code for Image Size?

There is no way to dynamically manipulate image size using HTML. HTML will allow you to set the specific width and height of an image for display, using the width and height attributes on the image tag. That process looks like this:

Be aware that adjusting the width and height parameters of an image could result in skewing the aspect ratio.

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