card_resize_images.py

# =========================================================
# Resize card images
# =========================================================
# Read card images, resize them, and write them to a
# new directory. The original image files are not
# changed.
# ---------------------------------------------------------
# Resizes card images because:
#   1. uniform size for card images
#   2. card game code need not spend time resizing
# ---------------------------------------------------------
# "import PIL.Image" is used to prevent namespace conflicts
# =========================================================

# ---------------------------------------------------------
# --- import
# ---------------------------------------------------------

import PIL.Image
import card_values as cv
import sys

# ---------------------------------------------------------
# --- which version of Python am I running?
# ---------------------------------------------------------

if sys.version_info.major == 3:
    from tkinter import *
    from tkinter.font import *
else:
    from Tkinter import *
    from tkFont import *

# ---------------------------------------------------------
# --- global variables
# ---------------------------------------------------------

imgHeight = 200
srcDir    = './cards-originals/'
dstDir    = './cards/'

# ---------------------------------------------------------
# --- functions
# ---------------------------------------------------------

def resize(img,src,dst,maxHeight):

    old = src + img
    new = dst + img

    i = PIL.Image.open(old)

    print('old width       : {}',format(i.size[0]))
    print('old height      : {}',format(i.size[1]))

    w = float(i.size[0])       # old image width
    h = float(i.size[1])       # old image height

    heightRatio = maxHeight/h

    newWidth = int(w * heightRatio)

    print('new height ratio: {}',format(heightRatio))
    print('new width       : {}',format(newWidth))
    print('new height      : {}',format(maxHeight))

    i = i.resize((newWidth,maxHeight),PIL.Image.ANTIALIAS)

    i.save(new)


# ---------------------------------------------------------
# --- main
# ---------------------------------------------------------

if __name__ == '__main__':

    fileNames = cv.cardsvalues.keys()

    c = 0

    for f in fileNames:
        print('Resizing: {}'.format(f))
        resize(f,srcDir,dstDir,imgHeight)
        c += 1

    print('{} files resized'.format(c))