Python Show-Me-the-Code 0,005th question batch Image Processing
Question 0,005th:You have a directory with a lot of photos installed. The size of these photos is not larger than the iPhone 5 Resolution.
Idea: traverse the images in the directory and scale the images larger than the iPhone 5 Resolution. Use the Python PIL library to process the image. The iPhone 5 screen resolution is 640 × 1136. Scale the image larger than the resolution to a proper size and save it.
0005. Batch image processing. py
#! /Usr/bin/env python # coding: The utf-8import Image, OS # source directory myPath = '/home/bill/Pictures/' # output directory outPath = '/home/bill/Pictures/output/'def processImage (filesource, destsource, name, imgtype ): '''filesource is the directory for storing the image to be converted. destsource is the directory for storing the output converted image. name is the file name. imgtype is the file type ''' imgtype = 'jpeg 'if imgtype = '.jpg 'else' png '# Open the Image im = Image. open (filesource + name) # scale ratio rate = max (im. size [0]/640.0 if im. size [0] & gt; 640 else 0, im. size [1]/1136.0 if im. size [1] & gt; 1136 else 0) if rate: im. thumbnail (im. size [0]/rate, im. size [1]/rate) im. save (destsource + name, imgtype) def run (): # Switch to the source directory and traverse all image OS in the source directory. chdir (myPath) for I in OS. listdir (OS. getcwd (): # Check the suffix postfix = OS. path. splitext (I) [1] if postfix = '.jpg 'or postfix = '.png': processImage (myPath, outPath, I, postfix) if _ name _ = '_ main _': run ()