Welcome, guest | Sign In | My Account | Store | Cart

Simple GUI to allow converting images from one format to another. Available formats are: .gif .jpg .png .tif .bmp Uses PIL.

Python, 120 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env python

"""Program for converting image files from one format
to another. Will convert one file at a time or all
files (of a selected format) in a directory at once.
Converted files have same basename as original files.

Uses workaround: askdirectory() does not allow choosing
a new dir, so asksaveasfilename() is used instead, and
the filename is discarded, keeping just the directory.
"""
import os, os.path, string, sys
from Tkinter import *
from tkFileDialog import *
import Image

openfile = '' # full pathname: dir(abs) + root + ext
indir = ''
outdir = ''
def getinfilename():
    global openfile, indir
    ftypes=(('Gif Images', '*.gif'),
            ('Jpeg Images', '*.jpg'),
            ('Png Images', '*.png'),
            ('Tiff Images', '*.tif'),
            ('Bitmap Images', '*.bmp'),
            ("All files", "*"))
    if indir:
        openfile = askopenfilename(initialdir=indir,
                                   filetypes=ftypes)
    else:
        openfile = askopenfilename(filetypes=ftypes)
    if openfile:
        indir = os.path.dirname(openfile)

def getoutdirname():
    global indir, outdir
    if openfile:
        indir = os.path.dirname(openfile)
        outfile = asksaveasfilename(initialdir=indir,
                                    initialfile='foo')
    else:
        outfile = asksaveasfilename(initialfile='foo')
    outdir = os.path.dirname(outfile)

def save(infile, outfile):
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print "Cannot convert", infile

def convert():
    newext = frmt.get()
    path, file = os.path.split(openfile)
    base, ext = os.path.splitext(file)
    if var.get():
        ls = os.listdir(indir)
        filelist = []
        for f in ls:
            if os.path.splitext(f)[1] == ext:
                filelist.append(f)
    else:
        filelist = [file]
    for f in filelist:
        infile = os.path.join(indir, f)
        ofile = os.path.join(outdir, f)
        outfile = os.path.splitext(ofile)[0] + newext
        save(infile, outfile)
    win = Toplevel(root)
    Button(win, text='Done', command=win.destroy).pack()

# Divide GUI into 3 frames: top, mid, bot
root = Tk()
topframe = Frame(root,
                 borderwidth=2,
                 relief=GROOVE)
topframe.pack(padx=2, pady=2)

midframe = Frame(root,
                 borderwidth=2,
                 relief=GROOVE)
midframe.pack(padx=2, pady=2)

botframe = Frame(root)
botframe.pack()

Button(topframe,
       text='Select image to convert',
       command=getinfilename).pack(side=TOP, pady=4)

multitext = """Convert all image files
(of this format) in this folder?"""
var = IntVar()
chk = Checkbutton(topframe,
                  text=multitext,
                  variable=var).pack(pady=2)
Button(topframe,
       text='Select save location',
       command=getoutdirname).pack(side=BOTTOM, pady=4)


Label(midframe, text="New Format:").pack(side=LEFT)
frmt = StringVar()
formats = ['.bmp', '.gif', '.jpg', '.png', '.tif']
for item in formats:
    Radiobutton(midframe,
                text=item,
                variable=frmt,
                value=item).pack(anchor=NW)

Button(botframe, text='Convert', command=convert).pack(side=LEFT,
                                                       padx=5,
                                                       pady=5)
Button(botframe, text='Quit', command=root.quit).pack(side=RIGHT,
                                                      padx=5,
                                                      pady=5)

root.title('Image Converter')
root.mainloop()

Why someone might want this: I needed this tool when I was making .avi's from my CAD program. My CAD program spits out images in .bmp format (f1.bmp, f2.bmp, f3.bmp ... fn.bmp) but my avi software needs .jpg format. So, now with a couple of clicks, I get a folder full of jpg's (f1.jpg, f2.jpg, f3.jpg, ...fn.jpg) which can be assembled into an avi, (or gif's which can be assembled into an animated gif).

Why I chose this particular solution: Previously, I wrote a simple shell script to do this on unix, using the ImageMagick 'convert' command. But when my unix machine at work got retired and all I had was NT, I decided it was time to write this python script.

Known issues: When selecting the location where the new file is to be written, I want the dialog to give me the option of being able to create a new directory. On Windows NT, the select folder dialog doesn't allow me to create a new folder. As a workaround, I use the save file dialog instead, which allows creating a new folder, but I have to use a dummy filename, which then gets discarded.

4 comments

Jody Burgess 19 years, 8 months ago  # | flag

Image Converter. This works great. Do you know where I can find a good and cheap solution to converting a Group 3/4 Tiff or jpg to PCL or PostScript code?

Thanks

David VandeBunte 12 years, 8 months ago  # | flag

Thanks a ton it did just what it was supposed to (after getting PIL)!

s_h_a_i_o 12 years, 7 months ago  # | flag

In order to work properly, I needed change the line 15 [import Image] to [from PIL import Image]. Very useful recipe, thanks a lot. It would be great to add a 'recursive' feature, and a 'delete original image' feature.

s_h_a_i_o 12 years, 7 months ago  # | flag

Please check an upgraded version (file deletion and recursive file picking) at http://code.activestate.com/recipes/577886-convert-image-format/