找回密码
 立即注册
搜索
热搜: Excel discuz
查看: 2716|回复: 2

[项目代码] 遍历所有图片,并在图片上加上文字(图片的名称)

[复制链接]

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750848
发表于 2021-7-30 13:32:41 | 显示全部楼层 |阅读模式
  1. from PIL import ImageFont
  2. from PIL import Image
  3. import os
  4. from PIL import ImageDraw
  5. name = []
  6. path = []
  7. for lujing,wenjianjia,wenjian in os.walk('D:\练习Python\新建文件夹'):
  8.     for file in os.scandir(lujing):
  9.         #print(file.name)
  10.         name.append(file.name)
  11.     #print(lujing)
  12.         j = lujing + '\\'+file.name
  13.         #print(j)
  14.         path.append(j)
  15. zidian = dict(zip(name,path))
  16. #print(zidian)
  17. for name,path in zidian.items():
  18.     imageFile = path
  19.     img = Image.open(imageFile)
  20.     font = ImageFont.truetype("C:\Windows\Fonts\STZHONGS.TTF", 40)
  21.     word = name
  22.     width = img.width
  23.     height = img.height
  24.     #print(width,height)
  25.     position = (100, height*0.6)
  26.     color = (0,0,0)
  27.     draw = ImageDraw.Draw(img)
  28.     draw.text(position, word, color, font=font)
  29.     # 保存图片
  30.     img.save(imageFile)
复制代码



回复

使用道具 举报

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750848
 楼主| 发表于 2021-7-30 13:33:26 | 显示全部楼层
目前来说,不能遍历子文件夹,以后有时间了再改进
回复

使用道具 举报

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750848
 楼主| 发表于 2021-7-30 13:47:48 | 显示全部楼层
包含子目录的版本代码:
  1. from PIL import ImageFont
  2. from PIL import Image
  3. import os
  4. from PIL import ImageDraw
  5. name = []
  6. path = []
  7. for lujing,wenjianjia,wenjian in os.walk('D:\练习Python\新建文件夹'):
  8.     for file in os.scandir(lujing):
  9.         #print(file.name)
  10.         if file.name.endswith('jpg'):

  11.             name.append(file.name)
  12.     #print(lujing)
  13.         j = lujing + '\\'+file.name
  14.         #print(j)
  15.         if j.endswith('jpg'):
  16.             path.append(j)
  17. zidian = dict(zip(name,path))
  18. #print(zidian)
  19. for name,path in zidian.items():
  20.     imageFile = path
  21.     #print(name)
  22.     #print(path)
  23.     img = Image.open(imageFile)
  24.     font = ImageFont.truetype("C:\Windows\Fonts\STZHONGS.TTF", 40)
  25.     word = name
  26.     width = img.width
  27.     height = img.height
  28.     #print(width,height)
  29.     position = (100, 100)
  30.     color = (255,0,0)
  31.     draw = ImageDraw.Draw(img)
  32.     draw.text(position, word, color, font=font)
  33.     # 保存图片
  34.     img.save(imageFile)
复制代码




回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|五花八门论坛 ( 豫ICP备15031300号-3 )

GMT+8, 2024-4-24 12:24 , Processed in 0.109918 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表