python使用PIL完成圖片的拼接和文字的添加


對兩張圖片進行拼接

圖片拼接,對於兩張相同寬度和不同高度的圖片進行拼接

1、首先獲取到圖片所在的位置,下面這段代碼完成對當前目錄下的image_test目錄進行遍歷,將所有jpg和png格式的圖片放到一個列表中

def picture_spell():
    # 獲取到圖片格式的文件的路徑
    path = "./image_test"
    result = []
    file_name_list = os.listdir(path)
    for file in file_name_list:
        if os.path.isfile(os.path.join(path, file)):
            if file.split(".")[1] in ['jpg', 'png']:
                result.append(os.path.join(path, file))
    print(result)

2、打開圖片,放到列表中

ims = list()
for fn in result:
    ims.append(Image.open(fn))

# 獲取各自的寬,高
width_one, height_one = ims[0].size
width_two, height_two = ims[1].size
print(width_one, height_one, width_two, height_two)

3、如果兩張圖片的寬度相同,不需要進行這一步操作,直接進行下一步操作即可,兩張圖片的寬度如若不同,進行此步操作

# 將兩張圖片轉化為相同寬度的圖片
new_img_one = ims[0].resize((1200, height_one), Image.BILINEAR)
new_img_two = ims[1].resize((1200, height_two), Image.BILINEAR)

4、創建一個新圖片,定義好寬和高,將兩張圖片paste進去保存即可
因個人需求,需要將高度小的放在最上面,所以對高度進行判斷識別,對於(0, 0, 1200, height_one),相當於(x, y, width, height),
第一張圖片起點都是0, 0 寬度固定1200, 高度為圖片的高度
第二張圖片起點為0和第一張圖片的高度, 寬度和第一張圖片一致1200,高度為第二張圖片的高度

target_images = Image.new('RGB', (1200, height_one + height_two))
if height_one < height_two:
    target_images.paste(new_img_one, (0, 0, 1200, height_one))
    target_images.paste(new_img_two, (0, height_one, 1200, height_one + height_two))
else:
    target_images.paste(new_img_two, (0, 0, 1200, height_two))
    target_images.paste(new_img_one, (0, height_two, 1200, height_one + height_two))
target_images.save("result.png")

完整代碼

下面為對圖片拼接的完整代碼,運行系統mac

import os
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw


def picture_spell():
    # 獲取到圖片格式的文件的路徑,此路徑為圖片所在的文件夾
    path = "./image_test"
    result = []
    file_name_list = os.listdir(path)
    for file in file_name_list:
        if os.path.isfile(os.path.join(path, file)):
            if file.split(".")[1] in ['jpg', 'png']:
                result.append(os.path.join(path, file))
    print(result)

    ims = list()
    for fn in result:
        ims.append(Image.open(fn))

    # 獲取各自的寬,高
    width_one, height_one = ims[0].size
    width_two, height_two = ims[1].size
    print(width_one, height_one, width_two, height_two)

    # 將兩張圖片轉化為相同寬度的圖片
    new_img_one = ims[0].resize((1200, height_one), Image.BILINEAR)
    new_img_two = ims[1].resize((1200, height_two), Image.BILINEAR)

    # 創建一個新圖片,定義好寬和高
    target_images = Image.new('RGB', (1200, height_one + height_two))
    if height_one < height_two:
        target_images.paste(new_img_one, (0, 0, 1200, height_one))
        target_images.paste(new_img_two, (0, height_one, 1200, height_one + height_two))
    else:
        target_images.paste(new_img_two, (0, 0, 1200, height_two))
        target_images.paste(new_img_one, (0, height_two, 1200, height_one + height_two))
        
    # 注意存儲路徑
    target_images.save("result.png")


if __name__ == '__main__':
    picture_spell()

對圖片的指定位置進行添加位置

對圖片的指定位置進行操作

img = Image.open("./c.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_set["type"], font_set["size"])
draw.text(font_set["location"], font_set["content"], font_set["color"], font=font)

完整代碼

下面是示例的完整代碼

"""
@File: point_picture.py
@CreateTime: 2020/3/17 下午8:28
@Desc: 位置:指的是圖片的x和y距離左上角起始點的坐標
可以是#00BBFF這樣的顏色值,也可以是(255,0,0)這樣的顏色值, (0,0,0)為黑色
"""
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw


def update_address():
    font_set = {
        "type": "./fonts/SourceHanSansCN-Normal.otf",
        "size": 16,
        "content": "要寫入的內容",
        "color": (0, 0, 0),
        "location": (122, 122),
    }

    # 打開需要進行編輯的圖片
    img = Image.open("./c.png")
    # 創建畫刷,用來寫文字到圖片上
    draw = ImageDraw.Draw(img)
    # 設置字體類型和大小
    font = ImageFont.truetype(font_set["type"], font_set["size"])
    # 根據位置、內容、顏色、字體來畫進圖片里,
    draw.text(font_set["location"], font_set["content"], font_set["color"], font=font)
    # 將操作后的圖片保存為result.png
    img.save("result.png")


if __name__ == '__main__':
    update_address()

可能遇到的問題

一、OSError: cannot write mode RGBA as JPEG

RGBA意思是紅色,綠色,藍色,Alpha的色彩空間,Alpha指透明度。而JPG不支持透明度,所以要么丟棄Alpha,要么保存為.png文件
解決辦法:
第一種

img=img.convert('RGB')
img.save('code.jpg')

第二種

img.save('code.png')

參考鏈接

OSError
簡書參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM