Python3 Beginners Practice Case (12) Save a picture from the source directory to the target directory script (use of image) according to the set longest edge parameter __python

Source: Internet
Author: User
Python3 Beginners Practice Case (12) Save a picture from the source directory to the target directory script (use of image) according to the set longest edge parameter

If we make a website for a client, the customer sends over a bunch of pictures that are usually taken from a cell phone or a digital camera. One problem is that these pictures are bigger. So we need to compress these images, which is what I write about the actual use of this script.

The key problem is the algorithm, for example, I require the longest edge of the picture 400px, then ideally, the processing state should be: The source picture size is 800*600, then the result is scaled 400*300 source picture size is 600*800, then the result is scaled 300*400 source picture size for 300* 200, because both width and height are smaller than the longest edges we set, so we do not do the same.

Well, if I don't have enough words for you to understand, I believe I should be able to understand my intentions through the detailed examples above. finally realize the source code

#!/usr/bin/env Python3 #-*-coding:utf-8-*-import argparse import os import imghdr from PIL import Image # error Exit Function def ERRMSN (MSN): Print (' \033[31merror:\033[0m ' + MSN) parser.print_usage () exit () # Find all pictures in the source directory and output the array def Findi MG (sdir): res = [] If not os.path.exists (sdir): Errmsn (' Source directory don\ ' t exist ') for F in
                Stdir (sdir): fp = Os.path.join (Sdir, F) if not Os.path.isdir (FP): if Imghdr.what (FP):
        Res.append (FP) If Len (res) = = 0:errmsn (' There is no image in the source directory ') Else:
        Return res # cycle scale All pictures def resizeimg (arr, size, Tdir, imgqual): for img in arr:simg = (IMG) simg_w = simg.size[0] Simg_h = simg.size[1] # If the original picture is wider than the set size, copy the artwork directly to the target directory if simg_w <= siz
            E and Simg_h <= (tdir + '/' + Os.path.basename (img), quality=imgqual) Else:
# Compare the width of the source picture, calculate the height of the processing            timg_w = Size Timg_h = Int (Size * simg_h/simg_w) if simg_w < simg_h: timg_w = Int (size * simg_w/simg_h) timg_h = size # shrink picture and save timg = Simg.resiz E ((timg_w, Timg_h), Image.antialias) (Tdir + '/' + Os.path.basename (img), quality=imgqual) print ('
        \033[32msuccess:\033[0m Task Finish ') # target directory processing function def checktargetdir (Sdir, Tdir): # Prompts the user to confirm if not tdir if the destination directory is empty: Print (' \033[33mwarning:\033[0m If the target directory isn\ ' t set, the processing ' results'll Cover the picture in the source directory\n ' \033[36mwhether to Continue (y/n) \033[0m ') confirm = Input (' Confirm: ') if Confirm in ("," Y ", ' y '): print (' \033[34minfo:\033[0m the target directory is
        ' + sdir ' return sdir else:exit () Else: # If the target directory is set, but does not exist, prompts the user whether to create the target directory If not os.path.exists (Tdir): Print (' Target directory don\ ' t exist\n ' \033[36mwhether to create ' target dire Ctory (y/n) \033[0m ') confirm = input (' Confirm: ') if confirm in (' ", ' y ', ' y '): os.m

Akedirs (Tdir) return Tdir else:exit () Else:return Tdir if __name__ = = "__main__": # SET command line arguments parser = argparse. Argumentparser () parser.description= ' Reduce ' the picture in the source directory and save it to the Targe T directory based on the longest side parameters ' Parser.add_argument ("-V", "--version", action= ' version ', version= '% (p ROG) S 1.0 ') parser.add_argument (' Size ', type=int, help= ' the max width or max height of a picture ') Parser.add_argu
    ment (' SourceDir ', help= ' Source directory ') parser.add_argument (' TargetDir ', help= ' Target directory ', nargs= '? ') Parser.add_argument (' Q ', '--quality ', Type=int, help= ' Save picture quality, defaultargs = Parser.parse_args () size = args.size Sdir = Args.sourcedir Imagearr = findimg (sdir) Tdir = Checktargetdir (sdir,args.targetdir) imgqual = args.quality or 60 # Perform processing resizeimg (Imagearr, size, Tdir, img qual)
Run Results

View Help Information

only the longest edge parameter and the source directory are set

The script prompts that the destination directory will overwrite the source file, return directly, or enter Y or Y to confirm, and enter N or N to exit the program.

The target directory is set, but the destination directory does not exist

The script prompts the destination directory not to exist, returns directly, or enters Y or y to create the directory, and enter n or N to exit the program.

Normal and error status

Code Resolution

First of all, to write a command line script, you need to deal with a variety of parameters, so the Argparse library is essential. For the use of this library, you can look at my third blog post in Python to learn more about the use of the Argparse command line parameter library, which I will not elaborate on here.

Common uses of Python OS libraries for folders

# Determine if the directory exists
os.path.exists (__dir__)
# Determine if the file exists
Os.path.isfile (__file__)
# Determine if the path is a folder
Os.path.isdir (__path__)
# Create a multi-tiered folder (you can also create a Single-layer folder)
os.makedirs (__path__)
# Get file name
based on path Os.path.basename (__path__)

More to view documents Https://

For image processing, you can view the official documentation for the Python PIL

To be simple, you can view the the Liao Xuefeng article 00140767171357714f87a053a824ffd811d98a83b58ec13000

Turn around and try to write a GUI with TK because it's really practical.

More content in the source code has been commented.

This article by Fungleo Original, allow reprint, but reprint must retain the first link.

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: 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.