• 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
    简书参考

  • 相关阅读:
    缓存与清除缓存
    PHP文件缓存与memcached缓存 相比 优缺点是什么呢
    memcached的基本命令(安装、卸载、启动、配置相关)
    54点提高PHP编程效率 引入缓存机制提升性能
    登陆类
    格式化金额数与自动四舍五入
    如何用Ajax传一个数组数据
    CodeIgniter的缓存机制与使用方法
    CI框架缓存的实现原理
    PHP导出数据库方法
  • 原文地址:https://www.cnblogs.com/ppwang06/p/pillow.html
Copyright © 2020-2023  润新知