本人剛剛學(xué)習(xí)python,發(fā)現(xiàn)python有很多有趣的地方,它能夠很容易的編寫出一些小工具。前幾天在論壇閑逛就看到了一個(gè)用Python發(fā)一個(gè)高逼格的朋友圈的文章,具體內(nèi)容就是把一個(gè)圖片經(jīng)過(guò)切割處理成九張圖片,如下圖所示。
朋友圈的展示如下
首先給大家介紹一個(gè)Python庫(kù):PIL(Python Image Library)
PIL是一個(gè)功能非常強(qiáng)大的Python圖像處理標(biāo)準(zhǔn)庫(kù),但是呢,由于PIL支持Python2.7,所以使用Python3的程序猿們又在PIL的基礎(chǔ)上分離出來(lái)了一個(gè)分支,創(chuàng)建了另外一個(gè)庫(kù)Pillow,是可以支持Python3的。
Pillow兼容了PIL的大部分語(yǔ)法,使用起來(lái)也非常的簡(jiǎn)單。
下面是具體的思路:

代碼:
from PIL import Image
import sys
#先將 input image 填充為正方形
def fill_image(image):
width, height = image.size
#選取長(zhǎng)和寬中較大值作為新圖片的
new_image_length = width if width > height else height
#生成新圖片[白底]
new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white') #注意這個(gè)函數(shù)!
#將之前的圖粘貼在新圖上,居中
if width > height:#原圖寬大于高,則填充圖片的豎直維度 #(x,y)二元組表示粘貼上圖相對(duì)下圖的起始位置,是個(gè)坐標(biāo)點(diǎn)。
new_image.paste(image, (0, int((new_image_length - height) / 2)))
else:
new_image.paste(image, (int((new_image_length - width) / 2),0))
return new_image
def cut_image(image):
width, height = image.size
item_width = int(width / 3) #因?yàn)榕笥讶σ恍蟹?張圖。
box_list = []
# (left, upper, right, lower)
for i in range(0,3):
for j in range(0,3):
#print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
box_list.append(box)
image_list = [image.crop(box) for box in box_list]
return image_list
#保存
def save_images(image_list):
index = 1
for image in image_list:
image.save('./result/hanxin'+str(index) + '.png', 'PNG')
index += 1
if __name__ == '__main__':
file_path = "hanxin.jpg"
image = Image.open(file_path)
#image.show()
image = fill_image(image)
image_list = cut_image(image)
save_images(image_list)
原文鏈接:
https://zhuanlan.zhihu.com/p/34658133?utm_source=qq&utm_medium=social&utm_oi=962865126642327552