Bulk Image-Resize in CSS, JavaScript, Python, Java, Node.js, and Other Languages

bulk image resize

What is Bulk Image-Resize?

Image resizing enlarges or reduces the size of an image, which typically involves increasing or reducing the number of pixels. Reducing the file size might result in loss of quality, pixelation, or blurriness. Also, failing to maintain the aspect ratio when resizing images “stretches” them out of proportion.

Bulk image-resizing techniques and tools enable you to resize images simultaneously, significantly reducing the time spent manually resizing one image at a time. This article explains how to resize images in bulk with the following:

Understanding Why You Would Want to Resize Images

The size of an image file uploaded to a website directly affects the website’s load time. Besides taking longer to load and negatively impacting the user experience and website performance, heavy image files can cause websites to become unresponsive or homepage sliders to run into problems.

Many websites, including social-media platforms, enforce restrictions on image size, meaning that you might need to scale images to fit the required dimensions, which might stretch or shrink them, resulting in quality issues. Alternatively, you can crop the images or create another instance that meets the requirements.

Image size also affects responsiveness. Modern websites are responsive, i.e., they adjust images, text, layout, and other components to fit the user’s screen resolution. Typically, responsive websites set images to 100% instead of a fixed size and then resize them according to the user’s screen resolution so that they fit in the container.

This is part of an extensive series of guides about machine learning.

Resize Images in CSS

You can resize images with CSS3 in one of three ways:

  • Absolute resizing. Specify the height and width values in an absolute-size format, such as pixels (px) and ems (em).
    • img{
        height: 100px;
        width: 200px;
      }
  • Resizing with the same aspect ratio. Specify the height or width value and set the other property to auto so as to retain the aspect ratio.
    • img{
        height: 100px;
        width: auto;
      }
  • Relative sizing. Resize images according to the parent <div> element or the current size of the viewport. (If the <image> element does not have a parent, CSS considers the parent to be the viewport.) With the object-fit:contain setting, CSS retains the image’s original dimensions and resizes it until the entire image is visible.
    • img{
        height: 100%;
        width: 100%;
        object-fit: contain;
      }

For more details, see Image Resizing: Manually With CSS and Automatically With Cloudinary.

Resizing Images in JavaScript

You can resize images dynamically with JavaScript with the zoomin() and zoomout() functions, offering viewers the zoom-in and zoom-out capabilities. These functions work with any tag with the ID zoom_img.

zoomin() function
This function scales up the image size by 100 pixels until the maximum size as specified is reached.

function zoomin(){
    var myImg = document.getElementById("zoom_img");
    var currWidth = myImg.clientWidth;
    // maximum defined size is 1000px
    if(currWidth <= 1000){
        myImg.style.width = (currWidth + 100) + "px";
    } 
}

Add a button to your HTML code so that viewers can zoom in on images with the relevant ID:

zoomout() function
This function scales down the image by 100 pixels until the minimum size as specified is reached.

function zoomout(){
    var myImg = document.getElementById("zoom_img");
    var currWidth = myImg.clientWidth;
    // minimum defined size is 50px
    if(currWidth >= 50){
        myImg.style.width = (currWidth—100) + "px";
    }
}

Add a button to your HTML code so that viewers can zoom out on images with the relevant ID:

Learn more in our detailed blog to javascript resizing.

Resize Images in Python

Pillow is a fork of the Python Imaging Library (PIL) that supports Python 3 and numerous image formats, including PNG, JPEG, and PPM. Before resizing images in Python, import PIL’s Image class to access its functions with which to transform the images in your code.

Here is the easiest way to resize an image in Pillow:

  1. Import the PIL’s image class:
    1. from PIL import Image
  2. Load the image from a file with the open() function:
    1. image = Image.open('myimage.jpg')

    The above command returns an Image object. In case of failure, the command returns an OSError exception.

  3. Call the resize() method on the new image instance, passing a tuple with two integers to specify the width and height you desire. In addition, call the save() function to save the image in the file system.
    1. new_image = image.resize((500, 500))
    2. new_image.save('myimage_500.jpg')

For more details, see Python image resizing.

Resize images in Java

You can perform image operations in Java with the java.awt.Image library, whose function getScaledInstance() resizes an image according to the following syntax:

getScaledInstance(width, height, Image.SCALE_SMOOTH);

width and height are self-explanatory. Image.SCALE_SMOOTH prioritizes smoothness when resizing to prevent rough edges from being displayed.

Bulk image resize

To resize an image in Java with getScaledInstance():

  1. Create a simple Java project and then a folder within the project called res. Place the image to be resized in that folder.
  2. Create a Java package for your Java class.
  3. Create a JFrame class, to which add a jLabel class for your image and set it to null layout. (The default setting scales the image to its original size.)
  4. Declare a class and load your image to it. The code below declares the ImageIcon class.private void scaleMouseClicked(java.awt.event.MouseEvent evt) {
    ImageIcon imageicon = new
    ImageIcon(getClass().getResource(“/res/image.jpg”));
  5. Invoke the getScaledInstance() function on the image. Note that in the code below, img is the variable name of jLabel. Finally, set the image to the new size.
    Image image = (imageicon).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH);
      imageicon = new ImageIcon(image);
      img.setIcon(imageicon);
    }

For more details, see resizing images in Java.

Resize Images in Node.js

Useful for scaling down images, npm’s sharp library supports JPEG, PNG, WebP, GIF, and AVIF, offering a higher performance than other libraries.

To resize an image with the sharp Node.js library:

  1. Install sharp:
    npm install sharp
  2. Define a block-scoped variable for sharp:
    const sharp = require('sharp');
  3. Load an image with the sharp object and call these two functions:
    • resize(), which accepts the width and height of the new image.
    • toFile(), which stores the new version of the file with a new file name.
    sharp('img1.jpg')
      .resize(200, 200)
      .toFile('rs_img1.jpg', function(err) {
        console.log(err)
      });

Note: The code near the bottom catches errors with function(err) and logs them for future reference.

For more details, see resizing images in Node.js. (COMING SOON)

Resize Image in jQuery

To resize an image in jQuery, you can use the .css() method, which specifies the width and height properties in CSS format.

To resize an image in jQuery with the .css() method:

  1. Add the following jQuery code:
    $(document).ready(function() {
      $('button').click(function() {
        $('#container').css({'width': '100px', 'height': 'auto'});
      });
    });

    On a click of the button created in step 2, .css() sets the width and height properties of the element with the ID container.

  2. Add a button to your HTML code to invoke the jQuery code:
    <img id="container" src='myimage.jpg' />
    <button>Resize</button>

For more details, see resizing images in JQuery. (COMING SOON)

Resize Images in C#

You can resize an image in C# with the Bitmap class, which performs multiple image operations, such as resizing with the Size parameter.

To resize an image in C# with the Bitmap class:

  1. Declare System.Drawing, the abstract base class that includes the Bitmap class:
    using System;
    using System.Drawing;
  2. Define a namespace and a class called Resizer:
    namespace resize_image
    {
      class Resizer
      {
        ...
      }
    }
  3. Add this code within your class to resize the image:
    public static Image resizeImage(Image imgToResize, Size size)
    {
      return (Image)(new Bitmap(imgToResize, size));
    }
    static void Main(string[] args)
    {
      string path = "C:\\myimage.jpg";
      Image img = Image.FromFile(path);
      Bitmap mybitmap = new Bitmap(img);
      Image resizedImage = resizeImage(mybitmap, new Size(400, 400));
    }

A few notes about this code:

  • The path variable defines the location of the image in the file system.
  • Bitmap is initialized as mybitmap for the pixel size of the image.
  • The resizeImage() function resizes the image to 400×400 px., creates a new instance, and casts it to the Image data type.
  • The new image instance resides in the resizedImage object.

For more details, see resizing images in C#.

Resize Images in React Native

You can resize images in React Native with the Fresco library-based Image component, which displays various types of images, including those from the network, static resources, temporary local images, and images from the local disk.

Fresco performs two image-resizing operations:

  • Resizing, which reduces the encoded image in memory to a smaller size and then creates a new, resized instance in memory. The original file remains unchanged.
  • Scaling, a hardware-accelerated canvas operation that displays the image in a larger or smaller size while retaining the size of the original bitmap.

Note that the following limitations:

  • Fresco supports the JPEG format only, scaling down images, not up.
  • The dimensions after resizing are within 1/8 of the original size, hence not exact.

 

To resize an image in React Native, use either of these functions:

resizeMethod()
This function resizes the image’s dimensions according to the following arguments:

  • auto — Resizes or scales the image based on heuristics.
  • resize — Resizes the image to the specified pixel size.
  • scale — Redraws the image in a different size without changing the underlying size.

resizeMode()
This function specifies what to do if the frame does not match the size of the raw image:

  • cover (default) — Scales the image uniformly while maintaining the aspect ratio. Ensures that the width and height are equal to or larger than the corresponding dimensions of the view.
  • contain — Scales the image uniformly, maintaining the aspect ratio so that the width and height are equal to or less than the corresponding dimensions of the view.
  • stretch — Scales the width and height independently, which might change the aspect ratio.
  • repeat — Repeats the image to cover the frame with the same size and aspect ratio. Scales down the image uniformly if it is larger than the view.
  • center — Centers the image in the view along the image’s width and height. Scales down the image uniformly if it is larger than the view.

For more details, see resizing images in React Native (COMING SOON)

Resizing Images in Bulk Through Automation With Cloudinary

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications.

You can also resize images through automation, focusing on the most important elements with AI, or adapt them to your website design by, for example, specifying the width, height, and aspect ratio as qualifiers for the new image instances. Cloudinary then automatically performs the resizing and cropping tasks to meet the criteria. No manual efforts are required.

See Additional Guides on Key Machine Learning Topics

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of machine learning.

Auto Image Crop

Authored by Cloudinary

Multi GPU

Authored by Run.AI

Advanced Threat Protection

Authored by Cynet

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better optimize bulk image resizing workflows across various languages and frameworks:

  1. Use batch processing for large image sets
    When dealing with hundreds or thousands of images, batch processing libraries like multiprocessing in Python or concurrent threads in Node.js can speed up operations significantly by parallelizing tasks. This prevents bottlenecks from single-threaded image processing.
  2. Consider hardware acceleration for real-time resizing
    For real-time applications, use libraries that support GPU acceleration, such as OpenCV with CUDA or TensorFlow.js for browser-based resizing. These offer considerable speedups compared to CPU-bound solutions when working with high-resolution images.
  3. Implement lazy loading for resized images in web projects
    Use the loading="lazy" attribute in HTML for resized images to improve web page performance. This ensures that images are only loaded when they come into the viewport, reducing the initial page load time.
  4. Create responsive image sets with automated breakpoints
    Tools like Cloudinary or the sharp library in Node.js can automatically create multiple versions of an image at different sizes. Use this to serve the optimal image based on the device’s screen resolution, saving bandwidth and improving performance.
  5. Automate format conversion for better compression
    Convert images to modern formats like WebP or AVIF during the resizing process. This typically results in smaller file sizes without noticeable quality loss. Implement automatic format detection to serve the best-supported format based on the user’s browser.
  6. Precompute image sizes for high-traffic sites
    For web platforms with high traffic, compute and cache image sizes ahead of time instead of resizing them on the fly. This can be done using server-side scripts in languages like Python or Node.js, combined with CDNs to cache and serve images quickly.
  7. Use content-aware scaling for complex images
    Implement content-aware algorithms, such as seam carving, which intelligently remove or add pixels in non-essential parts of the image. This prevents distortion when resizing complex images with a lot of details.
  8. Monitor memory usage for large image sets
    When processing images in bulk, especially with high-resolution files, memory consumption can spike and crash the application. Use streaming or chunked processing techniques in languages like Node.js or Python to handle images in parts, reducing memory footprint.
  9. Enable lossless resizing for image preservation
    Ensure that your resizing algorithm preserves important image metadata (like EXIF) and uses lossless compression where needed. Libraries like Pillow in Python and sharp in Node.js have options for this, which can be crucial for maintaining quality in professional photography.
  10. Create a test suite to validate resizing results
    Implement automated tests that check for common resizing errors (e.g., aspect ratio distortions or unwanted cropping). Use visual comparison tools like pixelmatch in JavaScript or compare_ssim in Python to ensure that your resizing algorithm is working as expected.

Resizing and cropping interactive demo

Last updated: Oct 1, 2024