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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python编程快速上手之第15章实践项目参考答案(17.7.1)相关的知识,希望对你有一定的参考价值。

#! 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)的主要内容,如果未能解决你的问题,请参考以下文章

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

python编程快速上手之第6章实践项目参考答案

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

python编程快速上手之第5章实践项目参考答案

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

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