img_pdf_png.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # coding=utf-8
  2. import os
  3. from datetime import datetime
  4. from PIL import Image
  5. def merge_images(image_folder, output_file, file_name, output_type, n=1):
  6. # 获取所有图像文件的列表
  7. image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')]
  8. # 计算每个小图像的大小和大图像的大小
  9. image_count = len(image_files)
  10. if image_count == 0:
  11. print('No image files found in the directory:', image_folder)
  12. return
  13. # 将所有小图像粘贴到新图像的正确位置
  14. target_img = {}
  15. new_img_size1 = 0
  16. new_img_size0 = 0
  17. for i, f in enumerate(image_files):
  18. idx = f.strip('.png')
  19. target_img[int(idx)] = f
  20. # 计算小图像的大小以及大图像的大小
  21. img = Image.open(os.path.join(image_folder, image_files[i]))
  22. img_size1 = int(img.size[1] / n)
  23. if i == 0:
  24. new_img_size0 = int(img.size[0] / n)
  25. new_img_size1 += img_size1
  26. # 创建一个新的大图像
  27. new_img = Image.new('RGB', (new_img_size0, new_img_size1), 'white')
  28. # 将所有小图像粘贴到新图像的正确位置
  29. now_height = 0
  30. for i in range(image_count):
  31. img = Image.open(os.path.join(image_folder, target_img[i]))
  32. # 纵向拼接图片
  33. new_img.paste(img, (0, now_height))
  34. # 当前粘贴高度自增已拼接的图片高度
  35. now_height += img.size[1]
  36. # 默认两种类型都生成
  37. if output_type == "":
  38. new_img.save(r'{}/{}.png'.format(output_file, file_name))
  39. new_img.save(r'{}/{}.pdf'.format(output_file, file_name), 'PDF', resolution=100.0, save_all=True)
  40. elif output_type == "img":
  41. new_img.save(r'{}/{}.png'.format(output_file, file_name))
  42. elif output_type == "pdf":
  43. new_img.save(r'{}/{}.pdf'.format(output_file, file_name), 'PDF', resolution=100.0, save_all=True)
  44. # 调用截图函数
  45. if __name__ == "__main__":
  46. # 用法示例
  47. image_folder = './imgs'
  48. output_file = './screenshot'
  49. file_name = 'output1'
  50. merge_images(image_folder, output_file, file_name=file_name)