Python Show-Me-the-Code 0,005th question batch Image Processing

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.