search
HomeWeb Front-endCSS TutorialConverting and Optimizing Images From the Command Line

Converting and Optimizing Images From the Command Line

Web page pictures usually account for more than 50% of the total page size. Unoptimized images will increase the number of bytes downloaded by users, resulting in longer page load times and consume more user data. Optimizing pictures can effectively solve these problems.

Researchers around the world are working to develop new image formats that significantly reduce file size while ensuring high visual quality, better than existing formats such as PNG or JPG. Although these new formats are still under development and browser support is limited, the WebP format has attracted much attention. In addition, the SVG format has also been widely used in recent years due to its lightweight nature, although it is different from raster images.

There are many methods for image optimization. This tutorial will write a Bash script to create and optimize images in different image formats (including JPG, PNG, WebP, and SVG). It aims to optimize the images before serving them, thereby reducing the byte size while ensuring the best visual effect.

All the images used in this tutorial have been uploaded to the GitHub repository. You are welcome to download and follow the tutorial.

set up

Before we start, we need to install the necessary dependencies. Since we use a Bash script, the operation will be performed on the command line.

Here are the dependency installation commands required to optimize images:

 sudo apt-get update
sudo apt-get install imagemagick webp jpegoptim optipng
npm install -g svgexport svgo

Before using these tools, it is important to understand their features:

  • ImageMagick: Supports various raster images
  • webp: Optimize WebP files
  • JPEGoptim: Optimize JPG/JPEG files
  • OptiPNG: Optimize PNG files
  • SVGO and svgexport: Node packages for optimizing SVG resources

We will use the images in the original-images directory in the GitHub repository. You can refer to Submit Record 3584f9b .

Note: It is highly recommended to back up your pictures before operation. We will run some programs that modify the picture, and while we plan to keep the original file, the wrong command may cause irreversible changes. So, back up any pictures you use in your actual project to avoid problems in the future.

Organize pictures

Now we have finished setting up. But before starting optimization, we should organize the files first. We can divide the images into different subdirectories according to the MIME type. In fact, we can create a new Bash script to automate this task!

The following code creates a script called organize-images.sh :

 #!/bin/bash

input_dir="$1"

if [[ -z "$input_dir" ]]; then
  echo "Please specify an input directory."
  exit 1
fi

for img in $( find $input_dir -type f -iname "*" );
do
  img_type=$(basename `file --mime-type -b $img`)
  mkdir -p "$img_type"
  rsync -a "$img" "$img_type"
done

If you are not familiar with scripting, this code may seem a bit complicated, but it is actually quite simple. We provide a input directory to the script where the script looks for images, recognizes their MIME type, then creates a subdirectory for each MIME type, and puts a copy of each image into the corresponding subdirectory.

Let's run it!

 bash organize-images.sh original-images

very good. The directory looks like this now. Now that our pictures are sorted out, we can start creating image variations in different formats. We will work on one image type at a time.

Convert to PNG

In this tutorial, we will convert three types of images to PNG: WebP, JPEG, and SVG. Let's start by writing a script called webp2png.sh , which, as the name implies, converts a WebP file to a PNG file.

 #!/bin/bash

input_dir="$1"

if [[ -z "$input_dir" ]]; then
  echo "Please specify an input directory."
  exit 1
fi

for img in $( find $input_dir -type f -iname "*.webp" );
do
  dwebp "$img" -o "${img%.*}.png"
done

The functions of the script are as follows:

  • input_dir="$1" : Stores command line input passed to the script.
  • if [[ -z "$input_dir" ]] : If the input directory is not defined, then the subsequent conditional statement is executed.
  • for img in $( find $input_dir -type f -iname "*.webp" ) : Loop through each file with a .webp extension in the directory.
  • dwebp "$img" -o "${img%.*}.png" : Convert WebP images to PNG format.

Let's run it:

 bash webp2png.sh webp

Now, we have PNG images in webp directory. Next, let's convert the JPG/JPEG file to PNG using another script called jpg2png.sh :

 #!/bin/bash

input_dir="$1"

if [[ -z "$input_dir" ]]; then
  echo "Please specify an input directory."
  exit 1
fi

for img in $( find $input_dir -type f -iname "*.jpg" -o -iname "*.jpeg" );
do
  convert "$img" "${img%.*}.png"
done

This script uses the convert command provided by the ImageMagick package we installed. Similar to the previous script, we provide an input directory containing JPEG/JPG images. The script looks for and creates a PNG variant for each matching image in that directory. If you look closely, we will find -o -iname "*.jpeg" is added to the find command. This is a logic or operator, and the script will look for all images with .jpg or .jpeg extensions.

The operation method is as follows:

 bash jpg2png.sh jpeg

Now that we have got the PNG variant from JPG conversion, we can do the same with the SVG file as well:

 #!/bin/bash

input_dir="$1"
width="$2"

if [[ -z "$input_dir" ]]; then
  echo "Please specify an input directory."
  exit 1
elif [[ -z "$width" ]]; then
  echo "Please specify image width."
  exit 1
fi

for img in $( find $input_dir -type f -iname "*.svg" );
do
  svgexport "$img" "${img%.*}.png" "$width":
done

This script adds a new feature. Since SVG is a scalable format, we can specify the width parameter to scale the SVG. We use the svgexport package we installed earlier to convert each SVG file to PNG:

 bash svg2png.sh svg xml 512

The commit record 76ff80a in the warehouse shows the results.

We have done a lot of work to create many PNG files based on other image formats. Before we start optimizing, we also need to do the same for the rest of the image formats.

...(The subsequent steps are similar to the original text, except for synonyms and sentence structure adjustments to the sentence to keep the original meaning unchanged. Due to space limitations, the pseudo-originality of the remaining part is omitted here.)

The above is the detailed content of Converting and Optimizing Images From the Command Line. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment