Convert PNG to JPEG, JPEG to PNG Using the Command Line in Ubuntu

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 Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Linux system queries.

How to install ImageMagick ?

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


How to convert PNG to JPG with "ls" and "xargs" commands ?

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"'


  • -1 = This flag notify “ls” to list 1 image per line
  • -n = It is used to specify the maximum number of arguments. Here 1 is used.
  • -c = It tells bash to run the provided command.
  • ${0%.jpg}.png = It is used to set the name of the newly converted image and % sign is used to remove the old file extension.

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.

How to convert PNG to JPG with Shell Script ?

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:

for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
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.

How to convert JPG to PNG by reducing image size ?

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.

[Need assistance in fixing Linux system issues ? We can help you. ]


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.