要實(shí)現(xiàn)多張圖片合成一個(gè)圖片,可以通過以下步驟使用 base64 編碼和解碼進(jìn)行實(shí)現(xiàn):
以下是一個(gè)示例 Python 代碼:
import base64
from PIL import Image
def combine_images(image_paths):
images = []
max_width = 0
total_height = 0
# 讀取圖片并計(jì)算合成后的圖片大小
for image_path in image_paths:
image = Image.open(image_path)
images.append(image)
max_width = max(max_width, image.width)
total_height += image.height
# 創(chuàng)建合成后的空白圖片
combined_image = Image.new('RGB', (max_width, total_height), 'white')
# 將每張圖片粘貼到合成圖片上
y_offset = 0
for image in images:
combined_image.paste(image, (0, y_offset))
y_offset += image.height
# 將合成圖片轉(zhuǎn)換為 base64 字符串
buffered = BytesIO()
combined_image.save(buffered, format='PNG')
base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
return base64_image
# 示例使用
image_paths = ['image1.jpg', 'image2.jpg', 'image3.jpg']
combined_image_base64 = combine_images(image_paths)
# 將合成后的圖片保存為文件
with open('combined_image.png', 'wb') as f:
f.write(base64.b64decode(combined_image_base64))
請注意,在示例代碼中使用了 Python 的 PIL
庫 (Python Imaging Library) 來處理圖片。你需要通過 pip install pillow
安裝該庫。