本章的resizeAndAddLogo.py程序使用PNG和JPEG文件,但pillow还支持许多格式,不仅仅是这两个。扩展resizeAndAddLogo.py,让它也能处理GIF和BMP图像。另一个小问题是,只有文件扩展名为小写时,程序才修改PNG和JPEG文件。例如,它会处理zophie.png,但不处理zophie.PNG。修改代码,让文件扩展名检查不区分大小写。最后,添加到右下角的徽标本来只是一个小标记,但如果该图像与徽标本身差不多大。修改resizeAndAddLogo.py,使得图像的宽度和高度必须至少是徽标的两倍,然后才粘贴徽标;否则,它应该跳过添加徽标。
时间: 2024-04-23 22:27:57 浏览: 15
您可以按照以下方式扩展和修改resizeAndAddLogo.py程序以处理GIF和BMP图像,并解决文件扩展名检查和徽标大小的问题:
```python
from PIL import Image
def resize_and_add_logo(filename, logo_filename):
img = Image.open(filename)
logo_img = Image.open(logo_filename)
logo_width, logo_height = logo_img.size
# Resize image if it's smaller than logo
if img.width < 2 * logo_width or img.height < 2 * logo_height:
return
# Resize image
img = img.resize((int(img.width / 2), int(img.height / 2)))
# Add logo to the bottom right corner
img.paste(logo_img, (img.width - logo_width, img.height - logo_height), logo_img)
# Save the modified image
img.save(f'resize_{filename}')
# Get all files in the current directory
import os
for filename in os.listdir('.'):
if not (filename.lower().endswith('.png') or filename.lower().endswith('.jpeg') or filename.lower().endswith('.gif') or filename.lower().endswith('.bmp')):
continue
resize_and_add_logo(filename, 'logo.png')
```
这样,resizeAndAddLogo.py程序将能够处理PNG、JPEG、GIF和BMP图像。文件扩展名检查不再区分大小写,因此无论是小写还是大写的扩展名,都能正确处理。另外,程序还会检查图像的宽度和高度是否至少是徽标的两倍,如果不满足条件,则跳过添加徽标的步骤。