码迷,mamicode.com
首页 > 编程语言 > 详细

python编程快速上手之第15章实践项目参考答案(17.7.1)

时间:2017-06-06 23:34:57      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:==   class   images   tor   快速   logs   设置   listdir   users   

#! python3
# resizeAndAddLogo.py - Resizes all images in current working directory to fit
# in a 300x300 square, and adds catlogo.png to the lower-right corner.

import os
from PIL import Image

os.chdir(C:\\Users\\Administrator\\Python35-32\\test\\kuaisu\\科幻)#设置文件路径
SQUARE_FIT_SIZE = 500 #设置图片修改大小
LOGO_SIZE=80     #设置LOGO大小,原图有800像素,太大了,设为80
LOGO_FILENAME = catlogo.png

logoIm = Image.open(LOGO_FILENAME)
logoIm = logoIm.resize((LOGO_SIZE, LOGO_SIZE))
logoWidth, logoHeight = logoIm.size

os.makedirs(withLogo, exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir(.):
    if not (filename.endswith(.png) or filename.endswith(.jpg)             or filename.endswith(.PNG) or filename.endswith(.JPG))        or filename == LOGO_FILENAME:
        continue # skip non-image files and the logo file itself
    
    im = Image.open(filename)
    im = im.convert(RGB)
    width, height = im.size

    # Check if image needs to be resized.
    if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
        # Calculate the new width and height to resize to.
        if width > height:
            height = int((SQUARE_FIT_SIZE / width) * height)
            width = SQUARE_FIT_SIZE
        else:
            width = int((SQUARE_FIT_SIZE / height) * width)
            height = SQUARE_FIT_SIZE

        # Resize the image.
        print(Resizing %s... % (filename))
        im = im.resize((width, height))

    # Add logo.
    if min(width, height) >= 2*int(LOGO_SIZE):       
      print(Adding logo to %s... % (filename))
      im.paste(logoIm, (width - logoWidth, height - logoHeight),logoIm)

    # Save changes.
      im.save(os.path.join(withLogo, filename))

 

python编程快速上手之第15章实践项目参考答案(17.7.1)

标签:==   class   images   tor   快速   logs   设置   listdir   users   

原文地址:http://www.cnblogs.com/flying-wyf/p/6954010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!