欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python+PIL實(shí)現(xiàn)批量在圖片上寫(xiě)上自定義文本

 更新時(shí)間:2024年11月28日 08:47:38   作者:一晌小貪歡  
Pillow 是一個(gè) Python 的圖像處理庫(kù),它是 Python Imaging Library (PIL) 的一個(gè)分支,并且增加了更多的功能,下面我們看看如何利用它實(shí)現(xiàn)批量在圖片上寫(xiě)上自定義的文本吧

背景

有時(shí)候我們需要將圖片上添加某一個(gè)編號(hào),但是如果圖片太多我們將會(huì)變得非常麻煩,這時(shí)候我們可以使用python對(duì)圖片進(jìn)行自然排序,接著在利用PIL 對(duì)圖片進(jìn)行編輯,添加上自增的編號(hào)

1、庫(kù)的介紹

Pillow 是一個(gè) Python 的圖像處理庫(kù),它是 Python Imaging Library (PIL) 的一個(gè)分支,并且增加了更多的功能。Pillow 庫(kù)使得加載、操作和保存多種圖像文件格式變得非常簡(jiǎn)單。它支持大量的圖像格式,包括常見(jiàn)的如 JPEG、PNG、BMP、GIF、PPM、TIFF 和一些更少見(jiàn)的格式。

主要特性

圖像處理: Pillow 提供了一系列的方法來(lái)對(duì)圖像進(jìn)行基本的操作,例如裁剪、旋轉(zhuǎn)、縮放、顏色轉(zhuǎn)換等。

圖像過(guò)濾器: 包括模糊、輪廓檢測(cè)、邊緣增強(qiáng)等濾鏡效果。

文本和圖形繪制: 可以在圖片上添加文字或繪制簡(jiǎn)單的圖形。

圖像序列處理: 支持處理 GIF 或其他格式的多幀圖像。

擴(kuò)展性: 用戶(hù)可以編寫(xiě)自己的圖像解碼器或格式處理器。

色彩模式支持: 支持多種色彩模式,比如 RGB、RGBA、CMYK 等。

2、庫(kù)的安裝

庫(kù)用途安裝
Pliiow處理圖片pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple/
natsort自然排序pip install natsort -i https://pypi.tuna.tsinghua.edu.cn/simple/
os獲取絕對(duì)路徑內(nèi)置庫(kù)無(wú)需安裝

3、核心代碼

自然排序

 # 獲取所有圖片文件 使用自然排序
 image_files = natsort.natsorted(os.listdir(input_folder))

創(chuàng)建自定義文本(包括樣式)

 # 創(chuàng)建繪圖對(duì)象
draw = ImageDraw.Draw(img)

 # 設(shè)置字體
 font_size = max(30, int(img_width * 0.03))
 font = ImageFont.truetype("simhei.ttf", font_size)

 # 文本內(nèi)容和顏色
 text = f"編號(hào):{index + 1}"
 text_color = (0, 0, 0)  # 黑色字體
 shadow_color = (0, 0, 0)  # 黑色陰影

 # 獲取文本尺寸
 bbox = draw.textbbox((0, 0), text, font=font)
 text_width = bbox[2] - bbox[0]
 text_height = bbox[3] - bbox[1]

 # 計(jì)算文本位置
 x = img_width - text_width - 190
 y = img_height - text_height - 30

 # 繪制文本陰影
 draw.text((x + 1, y + 1), text, font=font, fill=shadow_color)

 # 繪制文本
 draw.text((x, y), text, font=font, fill=text_color)

4、測(cè)試圖片創(chuàng)建腳本

# -*- coding: UTF-8 -*-
'''
@Project :測(cè)試 
@File    :創(chuàng)建隨機(jī)圖片.py
@IDE     :PyCharm 
@Author  :一晌小貪歡(278865463@qq.com)
@Date    :2024/9/27 下午11:04 
'''

import random
import os
from PIL import Image, ImageFont, ImageDraw

# 圖片命名為 name_list 中的隨機(jī)一個(gè),如張三_1.png,張三_2.png
name_list = ['張三', '李四', '王五', '趙六', '田七']

try:
    os.mkdir('圖片/圖片')
except FileExistsError:
    print('文件夾已存在')

# 清空文件夾 圖片
for i in os.listdir('圖片/圖片'):
    os.remove('./圖片/' + i)

# 創(chuàng)建50張隨機(jī)圖片
for i in range(50):
    width, height = 300, 300
    img = Image.new('RGB', (width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img)

    # 嘗試加載字體
    try:
        font = ImageFont.truetype('C:/Windows/Fonts/simhei.ttf', 65)
    except IOError:
        print("Font not found. Using default font.")
        font = ImageFont.load_default()

    random_name = random.choice(name_list)
    text = f"{random_name}_{i}"

    # 計(jì)算文本的邊界框
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    # 計(jì)算文本的起始位置
    x = (width - text_width) / 2
    y = (height - text_height) / 2

    # 在圖片上繪制文本
    draw.text((x, y), text, fill=(0, 100, 255), font=font)
    img.save(f'./圖片/{random_name}_{i}.png')
    print(f"{random_name}_{i}.png")

5、完整代碼

from PIL import Image, ImageDraw, ImageFont
import natsort
import os

def add_number_to_images(input_folder, output_folder):
    """
    在指定文件夾內(nèi)的每張圖片右下角添加編號(hào)
    :param input_folder: 輸入文件夾路徑
    :param output_folder: 輸出文件夾路徑
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 獲取所有圖片文件 使用自然排序
    image_files = natsort.natsorted(os.listdir(input_folder))


    for index, file_name in enumerate(image_files):
        # 打開(kāi)圖片
        img_path = os.path.join(input_folder, file_name)
        img = Image.open(img_path)

        # 獲取圖片大小
        img_width, img_height = img.size

        # 創(chuàng)建繪圖對(duì)象
        draw = ImageDraw.Draw(img)

        # 設(shè)置字體
        font_size = max(30, int(img_width * 0.03))
        font = ImageFont.truetype("simhei.ttf", font_size)

        # 文本內(nèi)容和顏色
        text = f"編號(hào):{index + 1}"
        text_color = (0, 0, 0)  # 黑色字體
        shadow_color = (0, 0, 0)  # 黑色陰影

        # 獲取文本尺寸
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]

        # 計(jì)算文本位置
        x = img_width - text_width - 190
        y = img_height - text_height - 30

        # 繪制文本陰影
        draw.text((x + 1, y + 1), text, font=font, fill=shadow_color)

        # 繪制文本
        draw.text((x, y), text, font=font, fill=text_color)

        # 保存處理后的圖片
        output_path = os.path.join(output_folder, file_name)
        img.save(output_path)

    print(f"所有圖片已處理并保存到:{output_folder}")

if __name__ == "__main__":
    # 輸入和輸出文件夾路徑
    input_dir = "圖片"  # 輸入圖片的文件夾
    output_dir = "處理后圖片"  # 處理后圖片的保存文件夾
    if not os.path.exists(input_dir):
        os.mkdir(output_dir)

    add_number_to_images(input_dir, output_dir)

效果圖

到此這篇關(guān)于Python+PIL實(shí)現(xiàn)批量在圖片上寫(xiě)上自定義文本的文章就介紹到這了,更多相關(guān)Python PIL圖片自定義文本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論