Scripting with ImageMagick
local graph
Chapter 13 — Scripting with ImageMagick
Section titled “Chapter 13 — Scripting with ImageMagick”ImageMagick is an awesome package of graphics manipulation tools. You can use these tools to perform many of the same jobs that you’d perform with GUI-type tools such as The GIMP and Adobe Photoshop. But, the ImageMagick tools are command-line tools, which allows you to use them in scripts in order to automate many types of jobs. These scripts can either be normal shell scripts, or scripts that use the ImageMagick scripting environment.
Topics in this chapter include:
- Converting non-standard filename extensions
- Installing ImageMagick
- Displaying images
- Viewing image properties
- Resizing and customizing images
- Batch-processing image files
- Using Fred’s ImageMagick scripts
If you’re ready, let’s get started.
Technical Requirements
Section titled “Technical Requirements”For this chapter, I’m using a desktop implementation of Fedora, because it comes with the newest version of ImageMagick. Debian 12 comes with an older version, but the commands and techniques that I present here also work on it.
Also, as always, you can download the scripts for this chapter by doing:
git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.gitConverting Non-standard Filename Extensions
Section titled “Converting Non-standard Filename Extensions”Before I even get to ImageMagick, I need to address something that’s a bit of a bugaboo with me. It’s that Linux and Unix operating systems are all case-sensitive, while other operating systems aren’t. So on Linux and Unix, somegraphic.png and somegraphic.PNG are two different files, while on Windows they both represent the same file. On Linux and Unix, it’s more proper to use lower-case letters in filename extensions. If you’re running a desktop implementation of either Linux or Unix, you might find that your GUI file manager won’t automatically open your graphics files in the graphics file viewer if the filename extensions for those files consist of upper-case letters. This wouldn’t be that big of a problem, except for the fact that certain Windows utilities and certain digital cameras always create graphics files with all upper-case letters in their filenames. Also, if you create a script to perform a batch operation on a whole directory full of images, having some filename extensions in upper-case letters and some in lower-case letters will mess you up. So, you’ll want to rename those files to match the Linux/Unix convention. If you have a whole directory full of files to convert, you’ll want to automate the process. So, check out this nifty rename_extension.sh script that can help you out:
#!/bin/bashfor file in *.JPG; do mv -- "$file" "${file%.JPG}.jpg"doneAs you see, this is just a simple for loop that searches for all files in the current directory that have the .JPG filename extension. The real magic is performed by the mv command that’s within the loop. (Remember that mv can be used to rename files and directories, as well as to move them to other locations.) The — sequence marks the end of the mv options list, and prevents problems with any files with filenames that begin with a -. At the end of the line, you see a variable expansion construct that replaces .JPG with .jpg for all filenames. And here, I need to add a word of caution.
Always be sure that your variable substitution constructs are built with a pair of curly braces, and not with a pair of parentheses. If you accidentally use parentheses instead of curly braces, the script will delete all of the files it finds, which probably isn’t what you want.
Anyway, let’s test the script to see what happens. Here are the contents of my graphics directory before I run the script:
[donnie@fedora script_test]$ lsrename_extension2.sh S1180001.JPG S1340001.JPG S1340003.JPGrename_extension.sh S1180002.JPG S1340002.JPG[donnie@fedora script_test]$Now, let’s run the script and then view the directory contents:
[donnie@fedora script_test]$ ./rename_extension.sh[donnie@fedora script_test]$ ls<!-- page: 360 (printed 355) -->rename_extension2.sh S118001.jpg S134001.jpg S134003.jpgrename_extension.sh S118002.jpg S134002.jpg[donnie@fedora script_test]$If you don’t want to deal with variable expansion or if you’re using a shell that doesn’t support it, you can instead use the basename utility, as you see here in the rename_extension2.sh script:
#!/bin/bashfor file in *.JPG; do mv -- $file "$(basename -- "$file" .JPG).jpg"doneThe basename utility works by stripping the directory path from a filename and, if specified, the filename extension as well. Here’s how it works when I just want to strip away the directory path:
[donnie@fedora ~]$ basename Pictures/script_test/rename_extension.shrename_extension.sh[donnie@fedora ~]$And, here’s how it works when I want to strip away both the directory path and the filename extension:
[donnie@fedora ~]$ basename Pictures/script_test/rename_extension.sh .shrename_extension[donnie@fedora ~]$Of course, this works with any filename extension, as you see here:
[donnie@fedora ~]$ basename Pictures/script_test/S134001.JPG .JPGS134001[donnie@fedora ~]$For me, .JPG and .MP4 files are the biggest problems, because my little Panasonic camcorder/camera saves its files with these naming formats. If you ever need to work with screenshots from a Windows machine, you’ll be working with .PNG files. It’s an easy matter to adapt either of the two scripts that I’ve just shown you to convert any of these filename extensions to all lower-case letters.
Now, with these preliminaries out of the way, let’s look at ImageMagick.
Installing ImageMagick
You’ll find ImageMagick in the repositories of OpenIndiana and pretty much every Linux distro. You’ll also find it in the repositories of FreeBSD and its desktop-oriented derivatives, such as GhostBSD and MidnightBSD. With only a couple of slight caveats, installation is quick and easy.
The first caveat concerns Debian. As you may already know, Debian tends to march to the beat of a different drummer, and is quite slow about getting up-to-date packages in its repositories.
So, if you’re installing ImageMagick on Debian 12 or older, you’ll get the older ImageMagick 6, rather than the current ImageMagick 7. (You might get version 7 if you switch to either Debian Testing or Debian Unstable, but I haven’t confirmed that since I prefer to stick with the stable branch.)
The other caveat is that there’s no consistency in how the various distros name the ImageMagick package. For example, the package name is ImageMagick on Fedora, imagemagick on Debian, OpenIndiana, and Alpine Linux, and ImageMagick7 on FreeBSD and its desktop derivatives. In all cases though, just install it using your distro’s normal package management tool.
If you’re running either macOS or Windows, you’ll find directions on how to install ImageMagick on them at the official ImageMagick website. (You’ll find the link to the ImageMagick website in the Further Reading section.)
Now that you have ImageMagick installed, let’s look at what we can do with it.
Displaying Images
To display an image, use the display command, like this:
donnie@fedora script_test]$ display S1180001.jpgI know, you’re wondering why I’m devoting a whole section of this chapter to just tell you that. Hang on, though, because there’s more.
Once you’ve opened the image, you can click either the right or the left mouse button to bring up a menu. The left mouse button brings up a menu that performs many of the image manipulation functions that you can do from the command-line. Here’s how it looks:
Figure 13.1: The ImageMagick left-click menu
The right-click menu is much simpler, as you see here:
Figure 13.2: The ImageMagick right-click menu
One thing you can do with the right-click menu is to display information about the image, which will look something like this:
Figure 13.3: Displaying image information from the right-click menu
You can learn how to use these menus by just playing around with them to see what everything does. But, as cool as all this is, it still doesn’t help us with shell scripting. So, we still need to see what we can do with ImageMagick from the command-line.
Viewing Image Properties
Use the identify command to view the properties of an image, like this:
[donnie@fedora script_test]$ identify S1180001.jpgS1180001.jpg JPEG 3968x2232 3968x2232+0+0 8-bit sRGB 1.90756MiB 0.000u 0:00.000[donnie@fedora script_test]$To see more information, use the -verbose option, like this:
[donnie@fedora script_test]$ identify -verbose S1180001.jpgImage:Filename: S1180001.jpgPermissions: rw-r--r--Format: JPEG (Joint Photographic Experts Group JFIF format)Mime type: image/jpeg...Number pixels: 8.85658MPixel cache type: MemoryPixels per second: 55.2201MPUser time: 0.160uElapsed time: 0:01.160Version: ImageMagick 7.1.1-15 Q16-HDRi x86_64 21298 https://imagemagick.org[donnie@fedora script_test]$One thing that we see about the above example is that it’s quite large, at 3968x2232 pixels and 1.90756MiB in size. I don’t need it to be that large, so let’s see about making it smaller.
Resizing and Customizing Images
Let’s say that I want to downsize my image to 1000x1000 pixels. I would do it like this:
[donnie@fedora script_test]$ convert -resize 1000x1000 S1180001.jpg S1180001_small.jpg[donnie@fedora script_test]$By default, the convert command maintains the original aspect ratio of the image. So, the size of my downsized image is actually 1000x563 pixels, as you see here:
[donnie@fedora script_test]$ identify S1180001_small.jpgS1180001_small.jpg JPEG 1000x563 1000x563+0+0 8-bit sRGB 328914B 0.000u0:00.000[donnie@fedora script_test]$Instead of specifying the size by pixels, you can specify the desired size in terms of a percentage of the original size, like so:
[donnie@fedora script_test]$ convert -resize 20% S1180001.jpg S1180001_small2.jpg[donnie@fedora script_test]$Now when I display the image, it will actually fit on my computer screen. Here’s how it looks:
Figure 13.4: Goldie, sleeping in my bedroom window sill
You can apply a special effect to an image at the same time that you resize it. For example, let’s turn this picture of Goldie into a charcoal drawing, like this:
[donnie@fedora script_test]$ convert -resize 15% -charcoal 2 S1180001.jpgS1180001_charcoal.jpg[donnie@fedora script_test]$The -charcoal option requires you to specify a number to determine the strength of the effect. In this case I just used -charcoal 2, which gives me just the effect that I want. (I started with -charcoal 15, but that didn’t look good at all.) Here’s how it turned out:
There’s such a wide array of effects that you can apply to your images, that it’s impossible for me to list them all here. To see the complete list, just view the convert man page.
One of the pleasant surprises about ImageMagick is that you can learn to do these sorts of things quite quickly, by consulting the magick and ImageMagick man pages, the ImageMagick website or the various tutorials that you’ll find on the either the web or on YouTube. In fact, every time I’ve ever tried to do anything like this with a GUI-type program, such as GIMP or PhotoShop, it always took me forever to figure it out.
Here’s something that’s always bugged me about tablets and smart phones is that when you put them into selfie mode to take a picture of yourself, the picture is always reversed. So, let’s say that I were to take selfie of me playing guitar. I’m a right-handed guitarist, but a selfie taken with my smartphone would make me look like a left-handed guitarist. (Paul McCartney, the world’s most famous living left-handed guitarist, would appear to be right-handed.) ImageMagick makes it easy to correct that, just by using convert with the -flop option, like so:
[donnie@fedora script_test]$ convert -flop S1180001_charcoal.jpg S1180001_charcoal_flop.jpgI don’t have any selfies handy at the moment, so I instead flopped Goldie’s picture. Here’s how it turned out:
Figure 13.6: Goldie’s picture, reversed
If you’ve ever made the mistake of holding your camera upside down while taking a picture, you can also reverse your pictures vertically by using the -flip option, like so:
donnie@fedora:~/Pictures/script_test$ convert -resize 15% -flip S1180001.jpgS1180001_flip.jpgdonnie@fedora:~/Pictures/script_test$Here’s how it turned out:
The last trick I’ll show you is how to convert from one image format to another. Just use convert without any option switches, like so:
[donnie@fedora script_test]$ convert S1180001_small2.jpg S1180001_small2.png[donnie@fedora script_test]$ ls -l *.png-rw-r--r--. 1 donnie donnie 494190 Dec 4 17:19 S1180001_small2.png[donnie@fedora script_test]$So, I now have a .png file to go along with the .jpg file. To see all of the image formats that ImageMagick can work with, just do:
[donnie@fedora ~]$ identify -list formatYou’re not always limited to just working with existing image files. You can also create original text image files with a variety of special effects. For example, let’s create a fancy image file of my name, like this:
[donnie@fedora Pictures]$ convert -size 320x115 xc:lightblue -font Comic-Sans-MS -pointsize 72 -fill Navy -annotate 0x0+12+55 'Donnie' -fill RoyalBlue -annotate 0x130+25+80 'Donnie' font_slewed.jpg[donnie@fedora Pictures]$Of course, the font that you specify must be installed on your system. In this case, I’m using the infamous Comic Sans font that everybody loves to hate. (It’s a Microsoft font, which I do have installed on this Fedora machine. I always install the full suite of Microsoft fonts on my Linux machines so that I can work with my publisher and my clients.) Also, note that you can’t have blank spaces in the font names. Replace each blank space with a dash, and you should be good. To understand the rest of the command, look in the ImageMagick man pages for explanations of all of the options. Anyway, here’s what my new image looks like:
Figure 13.8: The text image file that I created with ImageMagick
Pretty cool, right? It gets even more cool, when you look at the plethora of examples on the Font Effects page of the official ImageMagick documentation, which you can find here: https://imagemagick.org/Usage/fonts/
There’s a whole lot more that you can do with ImageMagick, but this is enough for now. Let’s now talk about using ImageMagick in shell scripts.
Batch-processing Image Files
Now, let’s say that you have a whole directory full of image files that you need to manipulate all in the same way. Using a GUI-type graphics program will be quite tedious, because you’ll only be able to work with one file at a time. With ImageMagick, just write a simple script to do the work for you. For example, let’s look at the resize.sh script:
#!/bin/bashfor picture in *.jpg; do convert -resize 15% "$picture" "${picture%.jpg}_small.jpg"doneAs you see, it’s really not that much different from the rename_extension.sh script that I’ve already shown you. Just a simple for loop and a bit of variable expansion is all you need. And of course, you can replace this -resize command with any other ImageMagick command you want.
Okay, this pretty much does it for the simple stuff. Let’s move on to the more complex stuff.
Using Fred’s ImageMagick Scripts
There’s a lot you can do with the simple types of ImageMagick commands that I’ve just shown you. For simple projects, you might not need anything more complex. But, if you’re a professional graphics artist, you might need more. You can create some awesome-looking images with awesome effects, but that might require using a very complex set of ImageMagick commands. Fortunately, there’s a way to cheat, because someone else has already done this work for you.
Fred’s ImageMagick Scripts are bash scripts that incorporate very complex sets of ImageMagick commands. As I’m writing this in December 2023, Mr. Fred Weinhaus has a total of 375 scripts that you can download from his site. They’re free of charge for personal use, but Fred does request that you contact him to arrange for payment if you need to use them for your business. I can’t even begin to describe all of the scripts and the effects that they can all create. So instead, I’ll just encourage you to go to Fred’s site and download some of the scripts for your own study. You can find Fred’s site here: http://www.fmwconcepts.com/imagemagick/
And, here’s what the site looks like:
Figure 13.9: Fred’s ImageMagick Scripts site
As you see in this graphic, you can get a description of what each script does by moving your cursor over the script name.
I believe that this about does it for an introduction to ImageMagick scripting. So, let’s summarize and move on.
Summary
ImageMagick is a great tool for both casual and professional graphics artists. You can perform some simple image manipulations with some very simple commands, or you can create awesome effects with more complex commands.
In this chapter, I started by explaining how to automate the process of changing non-standard filename extensions to the standard Linux/Unix format. I then explained how to install ImageMagick on a wide variety of operating systems. Next, I showed you how to display images, view image properties, and how to resize and customize images, all from the command-line. Finally, I showed you how to cheat a bit, by studying and trying out Fred’s ImageMagick scripts.
Of course, there’s still much more that you can do with ImageMagick than I can show you here. There are ImageMagick tutorials all over the place on the web, and you can easily find them with your favorite search engine. Better yet, go to YouTube, and search for ImageMagick tutorials there.
In the next chapter, I’ll show you how to squawk with awk. I’ll see you there.
Questions
-
Which of the following statements is false?
a. There’s not much you can do with ImageMagick, because it lacks a graphical user interface.
b. It’s sometimes easier to apply an effect with ImageMagick than it is with a GUI-type program.
c. You can batch process a directory full of graphics files by placing ImageMagick commands into a shell script.
d. ImageMagick is simple to use for simple tasks, but you can also perform more complex image manipulations with more complex scripts.
-
What are two methods that you can use to automate the process of changing filename extensions on a whole directory of graphics files?
a. Use command substitution
b. Use variable expansion
c. Use command expansion
d. Use the basename utility
-
Which ImageMagick command would you use to display image properties?
a. show
b. identify
c. show_properties
d. properties
Further Reading
-
bash—How do I change the extension of multiple files?: https://unix.stackexchange.com/ questions/19654/how-do-i-change-the-extension-of-multiple-files
-
ImageMagick.org: https://imagemagick.org/
-
Getting started with ImageMagick: https://opensource.com/article/17/8/imagemagick 367
-
Getting Started with ImageMagick: https://riptutorial.com/imagemagick
-
Manipulating Images with ImageMagick Command-line Tools: https://www.baeldung.com/linux/imagemagick-edit-images
-
Fred’s ImageMagick Scripts: http://www.fmwconcepts.com/imagemagick/
Answers
- a
- b and d
- b
Join our community on Discord!
Read this book alongside other users, Linux experts, and the author himself.
Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more. Scan the QR code or visit the link to join the community.