17.3 项目:添加徽标
17.7.1 实践项目:扩展和修正本章项目的程序
项目要求:
- 调整数千张图片的大小,并在每张图片的角上增加一个小徽标水印
- 图像必须至少是徽标的两倍的宽度和高度,然后才粘贴徽标。否则,它应该跳过添加徽标。
#! python3
# put watermark into many .jpg or .png
import os
# to make a watermark pic without background color
from PIL import Image
f = Image.open('wmk.png')
w,h = f.size
for x in range(w):
for y in range(h):
if f.getpixel((x,y)) == (255,255,255,255):
f.putpixel((x,y),(0,0,0,0))
f.save('wmk.png')
# in a 300x300 square, and adds catlogo.png to the lower-right corner.
SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'wmk.png'
logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size
# TODO: Loop over all files in the working directory.
for filename in os.listdir('.'):
if not (filename.lower().endswith('.jpg')
or filename.lower().endswith('.png')
or filename.lower().endswith('.gif')
or filename.lower().endswith('.bmp')) or (filename == LOGO_FILENAME):
continue
print(filename)
im = Image.open(filename)
width, height = im.size
# TODO: Check if image needs to be resized.
if width < 2 * logoWidth or height < 2 * logoHeight:
continue
elif width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
# TODO: 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
# TODO: Resize the image.
print('resizing the pic')
im = im.resize((width, height))
# TODO: Add the logo.
print('adding watermark into %s...' % filename)
im.paste(logoIm,(width - logoWidth, height - logoHeight),logoIm)
# TODO: Save changes.
im.save("added_" + filename)
17.7.2 实践项目:在硬盘上识别照片文件夹
项目要求:编写一个程序,遍历硬盘上的每个文件夹,找到可能的照片文件夹。当然,首先你必须定义什么是“照片文件夹”。假定就是超过半数文件是照片的任何文件夹。你如何定义什么文件是照片?首先,照片文件必须具有文件扩展名.png 或.jpg。此外,照片是很大的图像。照片文件的宽度和高度都必须大于 500 像素。
#! python3
# check pic dir
import os
from PIL import Image
for root, folders, files in os.walk('.'):
numPhoteFiles = 0
numNonPhotoFiles = 0
for file in files:
if not(file.lower().endswith('.jpg') or file.lower().endswith('.png')):
numNonPhotoFiles += 1
continue
im = Image.open(os.path.join(root,file))
width, height = im.size
if width < 500 and height < 500:
numNonPhotoFiles += 1
else:
numPhoteFiles += 1
if numPhoteFiles >= numNonPhotoFiles:
print(root)
17.7.3 实践项目:定制的座位卡
项目要求:使用 Pillow ???,为客人创建定制的座位卡图像。从 http://nostarch.com/automatestuff/下载资源文件guests.txt,对于其中列出的客人,生成带有客人名字和一些鲜花装饰的图像文件。
#! python3
# make card for different guests
import os
from PIL import Image, ImageDraw
os.chdir('card_dir')
with open('guests.txt') as f:
for guest in f.readlines():
im = Image.open('card_mo.png')
draw = ImageDraw.Draw(im)
draw.text((50,50),guest.strip().title(),fill='blue')
card_name = 'card_to_%s.png' % guest.strip()
im.save(card_name)
print('card-making work is done!')
环境:python3
想做这个系列文章,就是因为当时看这本书时,想看看网上有没更优美的解决,但是略难找到。所以就把自己的项目练习放在了一个txt文件中,现在把练习代码放到这里,有不足之处希望大家能给出指导意见及相互交流、提升。