Automate_image_conversion

At times when making latex report, I have to convert umpteen number of images from png to ps format There is easy command for conversion in linux from Imagemagick, you just need to type

In [ ]:
convert file_name.type file_name.new_type

But when need to convert many files, can use this small script that comes handy

Import sysem from os module for using operating system dependent functionality.

In [ ]:
import os
os.system(linux command)

Or another way is:
In jupyter you can use all linux commands by using exclamatory mark before the command

In [ ]:
!convert file_name.type file_name.new_type

Keep all the images need to be converted in one directory, this directory can contain other file types also, but we are going to check for file type and convert only them

In [1]:
import os
In [2]:
file_path = 'images_to_convert/'
In [6]:
fnames = os.listdir(file_path)

Now fnames is a list of all the file names(images) in that directory

File types of images you want to convert

In [7]:
old_file_type = '.png'
new_file_type = '.ps'

Below loop reads all the files, converts them to ps and removes the older files

In [8]:
for image in fnames:
    if image[-len(old_file_type):] == old_file_type:   #checking for only file type we want to change

        os.system('convert '+file_path+image+' '+  file_path+image.replace(old_file_type, '')+new_file_type)
        os.system('rm '+file_path+image)  #This deletes all the png files

Below cells are for styling, you can happily ignore them

In [17]:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))