#!/usr/bin/env python3
# filename
# vertical_split_merge.py
from PIL import Image
# 入力ファイルのパス
file_a = "A.png"
file_b = "B.png"
# 画像を読み込む
image_a = Image.open(file_a)
image_b = Image.open(file_b)
# 画像を縦方向に等分に分割する関数
def split_image_vertically(image):
width, height = image.size
left_box = (0, 0, width // 2, height) # 左半分
right_box = (width // 2, 0, width, height) # 右半分
left_part = image.crop(left_box)
right_part = image.crop(right_box)
return left_part, right_part
# AとBの画像をそれぞれ縦方向に分割
a_left, _ = split_image_vertically(image_a)
_, b_right = split_image_vertically(image_b)
# 左右のパーツの高さを一致させるため、共通の高さを決定(小さい方に合わせる)
common_height = min(a_left.height, b_right.height)
# 両方の画像パーツを上部から共通の高さでクロップ
a_left_cropped = a_left.crop((0, 0, a_left.width, common_height))
b_right_cropped = b_right.crop((0, 0, b_right.width, common_height))
# 結合後の画像サイズを計算
new_width = a_left_cropped.width + b_right_cropped.width
new_height = common_height
# 結合後の画像用のキャンバスを作成(背景は黒)
new_image = Image.new("RGB", (new_width, new_height))
# Aの左部分とBの右部分を貼り付け
new_image.paste(a_left_cropped, (0, 0)) # 左側にAの左部分
new_image.paste(b_right_cropped, (a_left_cropped.width, 0)) # 右側にBの右部分
# 結果を保存(PNG形式で保存。JPEG形式で保存する場合は、output_file を "output.jpg" に変更)
output_file = "output.png"
new_image.save(output_file)
print("新しい画像が保存されました:", output_file)
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme