In Linux, we can convert image file format from PNG to JPG and JPG to PNG with some command line tools. It will help compressing the image size and load the images more quicker.
There are different command line tools that can be used for such purposes.
Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Linux system queries.
Some of those tools are Convert which is a member of a ImageMagick tool. The Mogrify command can also be used to convert such image formats.
First, install the required package by using the following command:
$ sudo apt install imagemagick
Here, we are going to use convert command-line tools. The basic syntax for convert command is as follows:
$ convert [input-option] input-file [output-option] output-file
Here, "ls" command will list all the jpg images and xargs help to build and execute convert commands.
To convert JPG to PNG, run the command:
$ ls -1 *.jpg | xargs -n 1 bash -c 'convert "$0" "${0%.jpg}.png"'
To convert PNG to JPG
$ ls -1 *.png | xargs -n 1 bash -c 'convert "$0" "${0%.png}.jpg"'
Here,
You can notice that we have converted png to jpg format successfully with the above command. You can also convert jpg to png by using the above command.
We are going to write a small script to change png to jpg and vice versa. Such a script will look more clear. For example:
#!/bin/bash
for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
done
exit 0
Now save it as test.sh and run the command as below to make it executable. Now go to your directory where your images are saved and run the script.
You can also convert from jpg to png with a small change on the above script:
$ sudo chmod +x test.sh
$ ./test.sh
You will notice that we have converted png to jpg format successfully with the above command. You can also convert jpg to png too by interchanging .png and .jpg extensions.
To convert the image format from jpg to png by reducing it's image size, run the following command.
For example:
$ convert test.jpg -resize 40% test.png
Here, you can notice that we have converted jpg to png with reduced image size.
This article covers how to convert image extension from png to jpg and vice versa by using the useful command line tools such as ImageMagick command line tool.