1. 程式人生 > 實用技巧 >用 Python 實現朋友圈中的九宮格圖片,讓你的朋友圈從此逼格提升

用 Python 實現朋友圈中的九宮格圖片,讓你的朋友圈從此逼格提升

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理

以下文章來源於騰訊雲 作者:Python小二

( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載!還有海量最新2020python學習資料。 )

大家應該經常在朋友圈看到有人發九宮格圖片,其實質就是將一張圖片切成九份,然後在微信中一起發這九張圖即可。

說到切圖,Python 就可以實現,主要用到的 Python 庫為 Pillow,安裝使用 pip install pillow 即可,切圖的主要步驟如下:

  • 開啟要處理的圖片
  • 判斷開啟的圖片是否為正方形
  • 如果是正方形,就進行九等分,如果不是正方形,先用白色填充為正方形,再進行九等分
  • 儲存處理完的圖片
    主要實現程式碼如下:
# 填充新的 image
def fill_image(image):
    width, height = image.size
    _length = width
    if height > width:
        _length = height
    new_image = Image.new(image.mode, (_length, _length), color='white')
    if width > height:
        new_image.paste(image, (0, int((_length 
- height) / 2))) else: new_image.paste(image, (int((_length - width) / 2), 0)) return new_image # 裁剪 image def cut_image(image): width, height = image.size _width = int(width / 3) box_list = [] for i in range(0, 3): for j in range(0, 3): box = (j * _width, i * _width, (j + 1) * _width, (i + 1) * _width) box_list.append(box) image_list
= [image.crop(box) for box in box_list] return image_list # 將 image 列表的裡面的圖片儲存 def save_images(image_list, res_dir): index = 1 if not os.path.exists(res_dir): os.mkdir(res_dir) for image in image_list: new_name = os.path.join(res_dir, str(index) + '.png') image.save(new_name, 'PNG') index += 1

原圖:


效果圖: