想要縮放圖片的畫布大小,但直接使用 PIL 的 expand() 也會一併放大和縮小圖片內容。
PIL.ImageOps.
expand
(image, border=0, fill=0)[source]
Add border to the imageParameters
- image – The image to expand.
- border – Border width, in pixels.
- fill – Pixel fill value (a color value). Default is 0 (black).
Returns
An image.
上面第二個參數,可以比照 crop 傳入要 expand 的大小。
最佳解法,是服用下面的函數:
#!/usr/bin/env python
from PIL import Image
import math
def resize_canvas(old_image_path="314.jpg", new_image_path="save.jpg",
canvas_width=500, canvas_height=500):
"""
Resize the canvas of old_image_path.
Store the new image in new_image_path. Center the image on the new canvas.
Parameters
----------
old_image_path : str
new_image_path : str
canvas_width : int
canvas_height : int
"""
im = Image.open(old_image_path)
old_width, old_height = im.size
# Center the image
x1 = int(math.floor((canvas_width - old_width) / 2))
y1 = int(math.floor((canvas_height - old_height) / 2))
mode = im.mode
if len(mode) == 1: # L, 1
new_background = (255)
if len(mode) == 3: # RGB
new_background = (255, 255, 255)
if len(mode) == 4: # RGBA, CMYK
new_background = (255, 255, 255, 255)
newImage = Image.new(mode, (canvas_width, canvas_height), new_background)
newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))
newImage.save(new_image_path)
resize_canvas()
上面的解法會多2次 FILE I/O, 分別多 read/write 一次,也可以讓input/output 使用 PIL 物件傳遞:
def resize_canvas(im, canvas_width, canvas_height):
old_width, old_height = im.size
# Center the image
x1 = int(math.floor((canvas_width - old_width) / 2))
y1 = int(math.floor((canvas_height - old_height) / 2))
mode = im.mode
if len(mode) == 1: # L, 1
new_background = (255)
if len(mode) == 3: # RGB
new_background = (255, 255, 255)
if len(mode) == 4: # RGBA, CMYK
new_background = (255, 255, 255, 255)
newImage = Image.new(mode, (canvas_width, canvas_height), new_background)
newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))
return newImage
相關文章
In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing?
https://stackoverflow.com/questions/1572691/in-python-python-image-library-1-1-6-how-can-i-expand-the-canvas-without-resiz
How to Resize, Pad Image to Square Shape and Keep Its Aspect Ratio in Python
https://jdhao.github.io/2017/11/06/resize-image-to-square-with-padding/