首页 > 编程语言 >【Python】生成 gif图片

【Python】生成 gif图片

时间:2023-02-01 10:14:06浏览次数:38  
标签:name Python image list 生成 gif path frame

draw_gif.py

import os
import io
import imghdr
import imageio.v2 as imageio
from PIL import Image, ImageDraw, ImageFont
import numpy as np

from PIL import ImageFont, Image, ImageDraw, ImageSequence


def create_gif(image_list, gif_name, duration=0.35, date='未知时间'):
    frames = []
    result_list = []
    font = ImageFont.truetype('simfang', size=130)
    # 字体颜色
    fillColor = (255, 0, 0)
    # 文字输出位置
    position = (100, 100)
    # 输出内容
    str_ = date
    str_ = str_.encode('utf-8').decode('utf-8')

    for image_name in image_list:
        image_ = Image.fromarray(imageio.imread(image_name))
        temp_draw = ImageDraw.Draw(image_)
        # temp_draw.text(position, str_, font=font, fill=fillColor)  # 写入文字
        image_ = np.asarray(image_)
        result_list.append(image_)
        # frames.append(imageio.imread(image_name))
    imageio.mimsave(gif_name, result_list, 'GIF', duration=duration)


def main():
    orgin = r'E:\workfiles\temp_img\date_img'  # 首先设置图像文件路径
    files = os.listdir(orgin)  # 获取图像序列
    for file in files:
        file_path = os.path.join(orgin, file).replace('\\', '/')
        if os.path.isdir(file_path):
            image_list = []
            for i in os.listdir(file_path):
                path = os.path.join(file_path, i).replace('\\', '/')
                if imghdr.what(path) == 'png':
                    image_list.append(path)
            image_list = sorted(image_list)
            gif_name = os.path.join(orgin, file, file + '.gif')  # 设置动态图的名字
            duration = 0.5
            print('gif_name:', gif_name)
            print('image_list:', image_list)
            create_gif(image_list, gif_name, duration, file)  # 创建动态图


def watermark_on_gif(in_gif, out_gif, text='scratch8'):
    """本函数给gif动图加水印"""

    frames = []

    # myfont = ImageFont.truetype("msyh.ttf", 12)  # 加载字体对象

    im = Image.open(in_gif)  # 打开gif图形

    # water_im = Image.new("RGBA", im.size)  # 新建RGBA模式的水印图
    #
    # draw = ImageDraw.Draw(water_im)  # 新建绘画层
    #
    # draw.text((10, 10), text, fill='red')

    for frame in ImageSequence.Iterator(im):  # 迭代每一帧
        d = ImageDraw.Draw(frame)
        d.text((50, 100), "Hello World")
        del d

        # frame = frame.convert("RGBA")  # 转换成RGBA模式

        # frame.paste(water_im, None)  # 把水印粘贴到frame
        #
        # frames.append(frame)  # 加到列表中

        b = io.BytesIO()
        frame.save(b, format="GIF")
        frame = Image.open(b)

        # Then append the single frame image to a list of frames
        frames.append(frame)

    newgif = frames[0]  # 第一帧

    # quality参数为质量,duration为每幅图像播放的毫秒时间

    newgif.save(out_gif, save_all=True,
                append_images=frames[1:], quality=85, duration=100)
    # frames[0].save(r'E:\workfiles\temp_img\new_wind_2.gif', save_all=True, append_images=frames[1:])
    im.close()


if __name__ == '__main__':
    main()

draw_gif_v2.py


import os
import io
import imghdr
import imageio.v2 as imageio
from datetime import datetime
import numpy as np

from PIL import ImageFont, Image, ImageDraw, ImageSequence


def create_gif(image_list, gif_name, folder_name, duration=0.35):
    frames = []
    result_list = []

    for image_name in image_list:
        image_ = Image.fromarray(imageio.imread(image_name))
        temp_draw = ImageDraw.Draw(image_)
        #    输出内容
        if folder_name == '后向轨迹':
            font = ImageFont.truetype('simfang', size=60)
            # 字体颜色
            fillColor = (255, 0, 0)
            # 文字输出位置
            position = (30, 30)
            str_ = datetime.strptime('2022' + image_name.split('/')[-1].split('-')[1], '%Y%m%d').strftime('%Y-%m-%d')
        elif folder_name in ['卫星图-河南', '卫星图-三门峡']:
            font = ImageFont.truetype('simfang', size=20)
            # 字体颜色
            fillColor = (255, 0, 0)
            # 文字输出位置
            position = (10, 10)
            str_ = datetime.strptime('2022.' + image_name.split('/')[-1].strip('.png'), '%Y.%m.%d').strftime('%Y-%m-%d')
        else:
            str_ = 'no data'
        str_ = str_.encode('utf-8').decode('utf-8')
        if position and str_ and font and fillColor:
            temp_draw.text(position, str_, font=font, fill=fillColor)
        image_ = np.asarray(image_)
        result_list.append(image_)
        # frames.append(imageio.imread(image_name))
    imageio.mimsave(gif_name, result_list, 'GIF', duration=duration)


def main():
    orgin = r'E:\workfiles\temp_img\satellite_img'  # 首先设置图像文件路径
    files = os.listdir(orgin)  # 获取图像序列
    for file in files:
        file_path = os.path.join(orgin, file).replace('\\', '/')
        if os.path.isdir(file_path):
            image_list = []
            for i in os.listdir(file_path):
                path = os.path.join(file_path, i).replace('\\', '/')
                if imghdr.what(path) == 'png':
                    image_list.append(path)
            image_list = sorted(image_list)
            gif_name = os.path.join(orgin, file, file + '.gif').replace('\\', '/')  # 设置动态图的名字
            duration = 0.5
            print('gif_name:', gif_name)
            print('image_list:', image_list)
            create_gif(image_list, gif_name, file, duration)  # 创建动态图


def watermark_on_gif(in_gif, out_gif, text='scratch8'):
    """本函数给gif动图加水印"""

    frames = []

    # myfont = ImageFont.truetype("msyh.ttf", 12)  # 加载字体对象

    im = Image.open(in_gif)  # 打开gif图形

    # water_im = Image.new("RGBA", im.size)  # 新建RGBA模式的水印图
    #
    # draw = ImageDraw.Draw(water_im)  # 新建绘画层
    #
    # draw.text((10, 10), text, fill='red')

    for frame in ImageSequence.Iterator(im):  # 迭代每一帧
        d = ImageDraw.Draw(frame)
        d.text((50, 100), "Hello World")
        del d

        # frame = frame.convert("RGBA")  # 转换成RGBA模式

        # frame.paste(water_im, None)  # 把水印粘贴到frame
        #
        # frames.append(frame)  # 加到列表中

        b = io.BytesIO()
        frame.save(b, format="GIF")
        frame = Image.open(b)

        # Then append the single frame image to a list of frames
        frames.append(frame)

    newgif = frames[0]  # 第一帧

    # quality参数为质量,duration为每幅图像播放的毫秒时间

    newgif.save(out_gif, save_all=True,
                append_images=frames[1:], quality=85, duration=100)
    # frames[0].save(r'E:\workfiles\temp_img\new_wind_2.gif', save_all=True, append_images=frames[1:])
    im.close()


if __name__ == '__main__':
    main()

draw_gif_v3.py

import imageio
from PIL import Image, ImageDraw, ImageFont
import numpy as np

image_list = imageio.mimread(r'E:\workfiles\temp_img\2022-05-05\wind.gif')
# print(img_list)

font = ImageFont.truetype('simfang', size=130)
# 字体颜色
fillColor = (255, 0, 0)
# 文字输出位置
position = (100, 100)
#    输出内容
str_ = '2022-05-06'
str_ = str_.encode('utf-8').decode('utf-8')
print(len(str_))

# draw = ImageDraw.Draw(img_PIL)
# draw.text(position, str, font=font, fill=fillColor)
result_list = []
print(len(image_list))
for index, image_ in enumerate(image_list):
    image_ = Image.fromarray(image_)
    # if index <= 15:
    #     temp_draw = ImageDraw.Draw(image_)
    #     temp_draw.text(position, str_, font=font, fill=fillColor)
    # else:
    temp_draw = ImageDraw.Draw(image_)
    temp_draw.text(position, str_, font=font, fill=fillColor)

    image_ = np.asarray(image_)
    result_list.append(image_)

imageio.mimsave(r'E:\workfiles\temp_img\2022-05-05\new_wind.gif', result_list, 'GIF', duration=0.5)

标签:name,Python,image,list,生成,gif,path,frame
From: https://www.cnblogs.com/jessecheng/p/17081638.html

相关文章

  • @vue/cli 插件开发之自动根据目录列表生成别名配置
    1.相关文档@vue/cli官方文档@vue/cli@vue/cli插件开发指南@vue/cli2.插件命名规范为了让一个CLI插件在VueCLI项目中被正常使用,它必须遵循vue-cli-plugin-或......
  • python selenium之JS滚动条处理
    在网页当中,页面存在滚动条,而你要操作的元素在当前屏幕可见区域之外。那么需要使用滚动条滚动到该元素处,然后再操作它。selenium当中的使用execute_script方法执行js语句来......
  • logging --- Python 的日志记录工具
    logging ---Python的日志记录工具源代码: Lib/logging/__init__.pyImportant此页面仅包含API参考信息。教程信息和更多高级用法的讨论,请参阅基础教程进阶教......
  • python AttributeError: module 'matplotlib' has no attribute 'verbose'
    在pycharm中运行程序出现了该错误:AttributeError:module'matplotlib'hasnoattribute'verbose'  通过查询得知这其实不是程序的问题,也不是安装包的问题,是pycharm......
  • python UI自动化之JS定位
    前言本篇总结了几种js常用的定位元素方法,并用js点击按钮,对input输入框输入文本一、以下总结了5种js定位的方法除了id是定位到的是单个element元素对象,其它的都是elemen......
  • RabbitMq使用中常见错误--python版
    用python的pika库错误集 一、pika.exceptions.ProbableAuthenticationError:ConnectionClosedByBroker:(403)‘ACCESS_REFUSED-Loginwasrefusedusingauthentica......
  • python爬虫(三)- HTML解析之BeautifulSoup4
    BeautifulSoup可以从HTML、XML中提取数据。官网https://www.crummy.com/software/BeautifulSoup/官方中文文档https://www.crummy.com/software/BeautifulSoup/bs4/doc.......
  • PHP实现生成二维码代码展示
    本文为小伙伴们带来的是关于PHP实现生成二维码代码展示,前言为了满足用户渠道推广分析和用户账号绑定等场景的需要,公众平台提供了生成带参数二维码的接口。使用该接口可......
  • Python 基础语法介绍(二)
    一、概述上一篇文章:Python基础语法介绍(一),已经介绍了一部分基础知识了,这里就继续介绍python基础知识。二、函数函数是组织好的,可重复使用的,用来实现单一,或相关联功能的......
  • 62复习Python_OOP
    私有属性与函数python中_相当于java的保护__相当于私有如果需要在外部使用对象._类名__实例属性/方法(python存在类属性和实例属性)类方法和静态方法类方法......