detail_generate_base.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import settings
  2. import os
  3. try:
  4. is_test_plugins = settings.is_test_plugins
  5. except:
  6. is_test_plugins = False
  7. if is_test_plugins:
  8. from custom_plugins.plugins_mode.pic_deal import PictureProcessing
  9. else:
  10. from plugins_mode.pic_deal import PictureProcessing
  11. from PIL import Image
  12. import shutil
  13. from service.base import get_images, check_path, get_image_mask
  14. from natsort import ns, natsorted
  15. # import math
  16. from PIL import ImageFont
  17. import settings
  18. class DetailBase(object):
  19. def __init__(self, goods_no, goods_no_value: dict, out_put_dir, windows=None, excel_data=None,
  20. assigned_page_list=None, output_queue=None):
  21. self.goods_no = goods_no
  22. self.output_queue = output_queue
  23. self.out_put_dir = out_put_dir
  24. self.deal_pic_func_list = []
  25. self.goods_no_value = goods_no_value
  26. self.root = ""
  27. self.windows = windows
  28. self.template_name = None
  29. print(goods_no_value)
  30. # 重新解析为新的数据结构
  31. self.data = {}
  32. self.detailed_images = []
  33. self.assigned_page_list = assigned_page_list
  34. self.overlay_pic_dict = {}
  35. self.init()
  36. # for goods_art_no_dict in self.goods_no_value["货号资料"]:
  37. # print(goods_art_no_dict)
  38. #
  39. # raise 1
  40. if excel_data:
  41. ig_keys = ["模板名称"]
  42. for k, v in excel_data.items():
  43. if k not in ig_keys:
  44. self.goods_no_value[k] = v
  45. def del_detail_folder(self):
  46. out_path = "{out_put_dir}/{goods_no}".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
  47. if not os.path.exists(out_path):
  48. return
  49. try:
  50. shutil.rmtree(out_path)
  51. except BaseException as e:
  52. print("删除文件夹失败", e)
  53. def run_all(self):
  54. if self.template_name:
  55. self.out_put_dir = "{}/{}".format(self.out_put_dir, self.template_name)
  56. print("===================detailed_images=================")
  57. # 如果没有指定页面,则删除指定目录下的对应的详情文件夹
  58. if not self.assigned_page_list:
  59. self.del_detail_folder()
  60. detailed_images = self.deal_details()
  61. self.create_folder(self.out_put_dir)
  62. detail_path = "{out_put_dir}/{goods_no}/details".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
  63. self.create_folder(detail_path)
  64. self.save_to_png(detailed_images=detailed_images, detail_path=detail_path)
  65. # 生成拼接图
  66. self.generate_spliced_picture()
  67. # ------------移动其他图片---------------------
  68. # 获取主图模板列表
  69. main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)["main_pic_path_list"]
  70. if not main_pic_path_list:
  71. self.move_other_pic(move_main_pic=True)
  72. else:
  73. self.move_other_pic(move_main_pic=True)
  74. if not self.assigned_page_list:
  75. self.deal_all_main_pic()
  76. else:
  77. if "主图" in self.assigned_page_list:
  78. self.deal_all_main_pic()
  79. # ----------如果是红蜻蜓则创建同颜色下的其他货号颜色文件夹---------------
  80. if settings.PROJECT == "红蜻蜓":
  81. if "data_all_goods_art_info" in self.goods_no_value:
  82. # 数据格式:[{'number': '14250232', 'goods_art_no': 'AC52001173', 'color': '杏色'}, ]
  83. for pic_data in self.goods_no_value["货号资料"]:
  84. if "颜色名称" not in pic_data:
  85. continue
  86. color_name = pic_data["颜色名称"]
  87. color_file_path = "{out_put_dir}/{goods_no}/{goods_number}".format(out_put_dir=self.out_put_dir,
  88. goods_no=self.goods_no,
  89. goods_number=pic_data["编号"])
  90. for i in self.goods_no_value["data_all_goods_art_info"]:
  91. if color_name in i["color"]:
  92. new_path = "{out_put_dir}/{goods_no}/{goods_number}".format(out_put_dir=self.out_put_dir,
  93. goods_no=self.goods_no,
  94. goods_number="NUM{}".format(
  95. i["number"]))
  96. if not os.path.exists(new_path):
  97. # 创建文件夹
  98. os.makedirs(new_path)
  99. self.move_one_pic(color_file_path, new_path, "NUM{}".format(i["number"]))
  100. return True
  101. # 移动一张图片到新的文件夹
  102. def move_one_pic(self, old_path, new_path, new_name):
  103. image_file = os.listdir(old_path)[0]
  104. old_image_path = "{}/{}".format(old_path, image_file)
  105. image_e = os.path.splitext(image_file)[1]
  106. new_image_path = "{}/{}{}".format(new_path, new_name, image_e)
  107. shutil.copy(old_image_path, new_image_path)
  108. # 生成各个详情图切片
  109. def deal_details(self):
  110. detailed_images = []
  111. for index, func in enumerate(self.deal_pic_func_list):
  112. image_pp = func()
  113. if not self.assigned_page_list:
  114. self.image_list_append(detailed_images, image_pp)
  115. else:
  116. index = "{}".format(index + 1)
  117. if index in self.assigned_page_list:
  118. self.image_list_append(detailed_images, image_pp)
  119. else:
  120. self.image_list_append(detailed_images, {"mes": "不生成"})
  121. return [x for x in detailed_images if x]
  122. # 生成拼接的图片
  123. def generate_spliced_picture(self):
  124. detail_path = "{out_put_dir}/{goods_no}/details".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
  125. if not os.path.exists(detail_path):
  126. return
  127. detailed_images = []
  128. for image_data in get_images(detail_path):
  129. detailed_images.append(PictureProcessing(image_data["file_path"]))
  130. # 生成拼接图
  131. img = self.add_pic(detailed_images)
  132. join_path = "{out_put_dir}/{goods_no}/拼接图".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
  133. self.create_folder(join_path)
  134. img.save("{}/1.jpg".format(join_path), format="JPEG")
  135. def image_list_append(self, image_list: list, data):
  136. self.check_state_end()
  137. if isinstance(data, list):
  138. image_list.extend(data)
  139. else:
  140. image_list.append(data)
  141. def save_to_png(self, detailed_images, detail_path):
  142. self.check_state_end()
  143. for index, pp in enumerate(detailed_images):
  144. if isinstance(pp, dict):
  145. continue
  146. pp.im.save("{}/{}({}).png".format(detail_path, self.goods_no, str(index + 11).zfill(2)))
  147. def check_state_end(self):
  148. if self.windows is not None:
  149. if self.windows.state == 99:
  150. raise "用户主动取消"
  151. @classmethod
  152. def get_temp_pic_info(cls, root):
  153. """
  154. 获取详情页模板中的信息
  155. """
  156. main_pic_list = []
  157. mask_pic_list = []
  158. if os.path.exists(r"{}\main_image".format(root)):
  159. for _name in os.listdir(r"{}\main_image".format(root)):
  160. _path = r"{}\main_image\{}".format(root, _name)
  161. if os.path.isdir(_path):
  162. main_pic_list.append([x["file_path"] for x in get_images(_path)])
  163. mask_pic_list.append(
  164. [x["file_path"] for x in get_image_mask(_path)]
  165. )
  166. _l = get_images(r"{}\show".format(root))
  167. temp_pic_path = _l[0]["file_path"] if _l else None
  168. other_pic_list = [x["file_path"] for x in get_images(r"{}".format(root))]
  169. return {
  170. "main_pic_path_list": main_pic_list,
  171. "temp_pic_path": temp_pic_path,
  172. "mask_pic_list": mask_pic_list,
  173. "other_pic_path_list": other_pic_list,
  174. }
  175. def init(self):
  176. for goods_art_no_value in self.goods_no_value["货号资料"]:
  177. self.data[goods_art_no_value["货号"]] = {"pics": goods_art_no_value["pics"],
  178. "pic_is_deal": {}
  179. }
  180. def get_text_value(self, key, subsection_len=0):
  181. text = ""
  182. if key in self.goods_no_value:
  183. if self.goods_no_value[key]:
  184. text = str(self.goods_no_value[key])
  185. text = text.replace(r"\n", "\n")
  186. # if key in ["跟高", "鞋宽", "帮高", "脚掌围", "鞋长"]:
  187. # if text:
  188. # text = text.split(".")[0]
  189. if subsection_len != 0:
  190. text = text.split("\n")
  191. text = [x for x in text if x]
  192. if len(text) == 2:
  193. text_1 = text[0]
  194. text_2 = text[1]
  195. return text_1, text_2
  196. else:
  197. if text:
  198. text_1 = text[0]
  199. else:
  200. text_1 = ""
  201. text_2 = ""
  202. return text_1, text_2
  203. return text
  204. def create_folder(self, path):
  205. if not os.path.exists(path):
  206. os.makedirs(path)
  207. def get_all_process_pics(self):
  208. """
  209. 获取所有颜色的过程图片
  210. data = [
  211. {"货号": "",
  212. "素材": [{
  213. "名称": "俯视",
  214. "抠图": "路径1",
  215. "阴影": "路径2"
  216. }, ]},
  217. ]
  218. """
  219. return_data = []
  220. for goods_art_no in self.data:
  221. goods_art_no_dict = {"货号": goods_art_no,
  222. "素材": [],
  223. }
  224. # 图片数据重新排序
  225. pic_data = []
  226. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  227. root_path, file_name = os.path.split(pic_path)
  228. pic_data.append(file_name)
  229. pic_data = natsorted(pic_data, alg=ns.PATH)
  230. for file_name in pic_data:
  231. if "阴影" in file_name:
  232. _, action_name, _ = file_name.split("_")
  233. pic_path = self.data[goods_art_no]["pics"]["{}-阴影".format(action_name)]
  234. pic_cutout_path = self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)]
  235. if os.path.exists(pic_path) and os.path.exists(pic_cutout_path):
  236. goods_art_no_dict["素材"].append({"名称": action_name, "抠图": pic_cutout_path, "阴影": pic_path})
  237. return_data.append(goods_art_no_dict)
  238. return return_data
  239. def get_overlay_pic_from_dict(self, goods_art_no, color_name, bg_color) -> PictureProcessing:
  240. self.check_state_end()
  241. # 增加逻辑,获取任意货号下的组合图
  242. if "组合" in color_name:
  243. goods_art_no, color_name = self.get_all_scene_list(goods_art_no, color_name)
  244. key = "{}-{}-{}".format(goods_art_no, color_name, bg_color)
  245. if key in self.overlay_pic_dict:
  246. return self.overlay_pic_dict[key]
  247. if goods_art_no in self.data:
  248. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  249. if "阴影" in pic_name:
  250. action_name = pic_name.replace("-阴影", "")
  251. if action_name == color_name:
  252. pp1 = PictureProcessing(pic_path)
  253. pp2 = PictureProcessing(self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)])
  254. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(mode="pixel", base="width",
  255. value=1600)
  256. self.overlay_pic_dict[key] = pp1
  257. if key in self.overlay_pic_dict:
  258. return self.overlay_pic_dict[key]
  259. def image_init(self, bg_color=(246, 246, 246)):
  260. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  261. for goods_art_no in self.data:
  262. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  263. if "阴影" in pic_name:
  264. action_name = pic_name.replace("-阴影", "")
  265. pp1 = PictureProcessing(pic_path)
  266. pp2 = PictureProcessing(self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)])
  267. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(mode="pixel", base="width",
  268. value=1600)
  269. self.data[goods_art_no]["pic_is_deal"][action_name] = pp1
  270. # 获取任意货号的场景图,优先取指定货号;
  271. # 调整,按顺序从货号列表中提取所有组合图
  272. def get_all_scene_info(self, goods_art_no):
  273. data = []
  274. # 收集所有组合图
  275. # 找任意一个有组合图的货号
  276. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  277. _goods_art_no = goods_art_no_dict["货号"]
  278. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  279. for _view_name in _view_name_list:
  280. if "组合" not in _view_name:
  281. continue
  282. return _goods_art_no
  283. return goods_art_no
  284. def get_all_scene_list(self, goods_art_no, view_name: str):
  285. if "组合" == view_name:
  286. view_name = "组合1"
  287. try:
  288. view_index = int(view_name.replace("组合", "")) - 1
  289. except:
  290. return goods_art_no, "无法匹配"
  291. data = []
  292. # 收集所有组合图
  293. # 找任意一个有组合图的货号
  294. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  295. _goods_art_no = goods_art_no_dict["货号"]
  296. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  297. for _view_name in _view_name_list:
  298. if "组合" not in _view_name:
  299. continue
  300. data.append(
  301. {"goods_art_no": _goods_art_no,
  302. "view_name": _view_name,
  303. "real_view_name": "组合1" if _view_name == "组合" else _view_name
  304. }
  305. )
  306. if len(data) <= view_index:
  307. return goods_art_no, "无法匹配"
  308. else:
  309. data.sort(key=lambda x: x["real_view_name"], reverse=False)
  310. return data[view_index]["goods_art_no"], data[view_index]["view_name"]
  311. def image_one_pic(self, goods_art_no, name, bg_color=None, return_orign=None):
  312. # 增加逻辑,获取任意货号下的组合图
  313. if "组合" in name:
  314. print("324==== goods_art_no, name", goods_art_no, name)
  315. goods_art_no, name = self.get_all_scene_list(goods_art_no, name)
  316. print("324 goods_art_no, name", goods_art_no, name)
  317. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  318. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  319. if "阴影" in pic_name:
  320. action_name = pic_name.replace("-阴影", "")
  321. if name != action_name:
  322. continue
  323. pp1 = PictureProcessing(pic_path)
  324. pp2 = PictureProcessing(self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)])
  325. if not return_orign:
  326. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(mode="pixel", base="width",
  327. value=1600)
  328. return pp1
  329. else:
  330. return pp1, pp2
  331. if not return_orign:
  332. return None
  333. else:
  334. return None, None
  335. def move_other_pic(self, move_main_pic=True):
  336. # ------------------------------移动其他图片------------------------------
  337. goods_no_main_pic_number = 0
  338. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  339. if "800x800" not in goods_art_no_dict:
  340. continue
  341. if not goods_art_no_dict["800x800"]:
  342. continue
  343. goods_art_no = ""
  344. if "编号" in goods_art_no_dict:
  345. if goods_art_no_dict["编号"]:
  346. goods_art_no = goods_art_no_dict["编号"]
  347. if not goods_art_no:
  348. goods_art_no = goods_art_no_dict["货号"]
  349. # print("goods_art_no:", goods_art_no)
  350. # 移动颜色图=====================
  351. goods_art_no_f = "{}/{}/{}".format(self.out_put_dir, self.goods_no, goods_art_no)
  352. self.create_folder(goods_art_no_f)
  353. # 放入一张主图
  354. old_pic_path_1 = goods_art_no_dict["800x800"][0]
  355. shutil.copy(old_pic_path_1,
  356. "{}/{}{}".format(goods_art_no_f, goods_art_no, os.path.splitext(old_pic_path_1)[1]))
  357. # 把其他主图放入作为款号图=====================
  358. if move_main_pic:
  359. for pic_path in goods_art_no_dict["800x800"]:
  360. goods_no_main_pic_number += 1
  361. e = os.path.splitext(pic_path)[1]
  362. shutil.copy(pic_path,
  363. "{out_put_dir}/{goods_no}/{goods_no}({goods_no_main_pic_number}){e}".format(
  364. out_put_dir=self.out_put_dir, goods_no=self.goods_no,
  365. goods_no_main_pic_number=str(goods_no_main_pic_number + 10).zfill(2),
  366. e=e))
  367. def deal_all_main_pic(self):
  368. """
  369. 处理主图模板,如存在出图模板则进行对应处理
  370. """
  371. # 获取主图模板列表
  372. all_main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)["main_pic_path_list"]
  373. if not all_main_pic_path_list:
  374. return
  375. mask_pic_list = DetailBase.get_temp_pic_info(root=self.root)["mask_pic_list"]
  376. data = self.get_all_process_pics()
  377. print("========deal_all_main_pic=========主图相关素材:")
  378. view_list = ["组合", "组合2", "组合3", "组合4", "组合5", "组合6", "俯视", "侧视", "后跟", "鞋底", "内里", ]
  379. for _index, main_pic_path_list in enumerate(all_main_pic_path_list):
  380. self.check_state_end()
  381. out_path_root = "{out_put_dir}/{goods_no}/main_image_{_index}".format(
  382. out_put_dir=self.out_put_dir,
  383. goods_no=self.goods_no,
  384. _index=_index
  385. )
  386. check_path(out_path_root)
  387. if mask_pic_list[_index]:
  388. mask_pic = mask_pic_list[_index][0]
  389. else:
  390. mask_pic = None
  391. goods_no_main_pic_number = 10
  392. # g_index 为第几个颜色货号
  393. for g_index, goods_art_no_dict in enumerate(data):
  394. goods_art_no = goods_art_no_dict["货号"]
  395. # =====================重新指定=================================
  396. _material_sort_dict = {}
  397. for index, material_dict in enumerate(goods_art_no_dict["素材"]):
  398. name = material_dict["名称"]
  399. _material_sort_dict[name] = material_dict
  400. # ======================================================
  401. file_name_index = -1
  402. for view_name in view_list:
  403. # 组合图比较特殊,为全局获取
  404. if g_index != 0:
  405. if "组合" in view_name:
  406. continue
  407. if view_name not in _material_sort_dict:
  408. continue
  409. self.check_state_end()
  410. pp_jpg, pp_png = self.image_one_pic(goods_art_no, view_name, bg_color=None, return_orign=True)
  411. if not pp_jpg:
  412. continue
  413. file_name_index += 1
  414. # 获取对应主图模板
  415. if len(main_pic_path_list) < file_name_index + 1:
  416. main_pic_path = main_pic_path_list[-1]
  417. else:
  418. main_pic_path = main_pic_path_list[file_name_index]
  419. pp_bg = PictureProcessing(main_pic_path)
  420. original_width = pp_bg.width
  421. if original_width != 1600:
  422. pp_bg = pp_bg.resize(value=1600)
  423. if mask_pic:
  424. mask_bg = PictureProcessing(mask_pic)
  425. mask_bg = mask_bg.resize(value=1600)
  426. mask_box_im = mask_bg.get_im()
  427. box_size = mask_box_im.getbbox()
  428. result_image = mask_box_im.crop(box_size)
  429. mask_width, mask_height = result_image.size
  430. mask_x, mask_y = box_size[0], box_size[1]
  431. else:
  432. mask_width, mask_height = pp_bg.size
  433. mask_width, mask_height = int(mask_width * 12 / 16), int(mask_height * 12 / 16)
  434. mask_x, mask_y = int((pp_bg.size[0] - mask_width) / 2), int((pp_bg.size[1] - mask_height) / 2)
  435. if view_name != "后跟":
  436. pp_jpg = pp_jpg.resize(base_by_box=(mask_width, mask_height))
  437. pp_png = pp_png.resize(base_by_box=(mask_width, mask_height))
  438. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  439. p_x = mask_x + int((mask_width - pp_jpg.width) / 2)
  440. p_y = mask_y + int((mask_height - pp_jpg.height) / 2)
  441. pp_bg = pp_bg.to_overlay_pic_advance(mode="pixel", top_img=pp_jpg, base="nw",
  442. value=(p_x, p_y), top_png_img=pp_png)
  443. else:
  444. new_mask_width, new_mask_height = int(mask_width / 1.6), int(mask_height / 1.6)
  445. pp_jpg = pp_jpg.resize(base_by_box=(new_mask_width, new_mask_height))
  446. pp_png = pp_png.resize(base_by_box=(new_mask_width, new_mask_height))
  447. new_mask_x = int((mask_width - new_mask_width) / 2 + mask_x)
  448. new_mask_y = int((mask_height - new_mask_height) / 2 + mask_y)
  449. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  450. p_x = new_mask_x + int((new_mask_width - pp_jpg.width) / 2)
  451. p_y = new_mask_y + int((new_mask_height - pp_jpg.height) / 2)
  452. pp_bg = pp_bg.to_overlay_pic_advance(mode="pixel", top_img=pp_jpg, base="nw", value=(p_x, p_y),
  453. top_png_img=pp_png)
  454. goods_no_main_pic_number += 1
  455. out_pic_path = "{out_path_root}/{goods_no}({goods_no_main_pic_number}){pic_mode}".format(
  456. out_path_root=out_path_root,
  457. goods_no=self.goods_no,
  458. goods_no_main_pic_number=goods_no_main_pic_number,
  459. pic_mode=settings.OUT_PIC_MODE,
  460. )
  461. if settings.OUT_PIC_FACTOR > 1.0:
  462. print("图片锐化处理")
  463. pp_bg = pp_bg.sharpen_image(factor=settings.OUT_PIC_FACTOR)
  464. if original_width < 1600:
  465. pp_bg = pp_bg.resize(value=original_width)
  466. print("392 out_pic_path", out_pic_path)
  467. if settings.OUT_PIC_MODE == ".jpg":
  468. pp_bg.save_as_rgb(out_pic_path)
  469. else:
  470. pp_bg.save_as_png(out_pic_path)
  471. def add_pic(self, detailed_images):
  472. self.check_state_end()
  473. todo_detailed_images = []
  474. detailed_images = [x for x in detailed_images if x]
  475. if not detailed_images:
  476. return
  477. for i in detailed_images:
  478. if isinstance(i, list):
  479. for n in i:
  480. todo_detailed_images.append(n)
  481. else:
  482. todo_detailed_images.append(i)
  483. page_len = 0
  484. for index, pp in enumerate(todo_detailed_images):
  485. page_len += pp.height
  486. bg_im = Image.new("RGB", (pp.width, page_len), (255, 255, 255))
  487. n = 0
  488. for index, pp in enumerate(todo_detailed_images):
  489. bg_im.paste(pp.im, (0, n))
  490. n += pp.height
  491. return bg_im
  492. # 通用方法,用于写文字
  493. def add_text_list(self, text_list, spacing=5, base="wn", base_width=1600):
  494. text_list = [x for x in text_list if x["text"]]
  495. # print(text_list)
  496. # spacing 行间距
  497. text_image_list = []
  498. max_w = 0
  499. total_h = 0
  500. for text_data in text_list:
  501. _pp = PictureProcessing("RGBA", (base_width, 1200), (255, 255, 255, 0))
  502. if base == "wn" or base == "nw":
  503. align = "left"
  504. anchor = None
  505. value = (0, 250)
  506. if base == "cn" or base == "nc":
  507. align = "center"
  508. anchor = "mm"
  509. value = (int(base_width / 2), 250)
  510. if base == "en" or base == "ne":
  511. align = "right"
  512. anchor = "rs"
  513. value = (base_width - 10, 250)
  514. _pp = _pp.get_text_image_advanced(
  515. value=value,
  516. font=text_data["font"],
  517. text=text_data["text"],
  518. align=align,
  519. anchor=anchor,
  520. spacing=5,
  521. fill=text_data["fill"],
  522. return_mode="min_image",
  523. margins=(0, 0, 0, 0)
  524. )
  525. text_image_list.append(_pp)
  526. if _pp.width > max_w:
  527. max_w = _pp.width
  528. total_h += _pp.height
  529. if "spacing" in text_data:
  530. total_h += text_data["spacing"]
  531. if not text_image_list:
  532. return None
  533. #
  534. bg = PictureProcessing("RGBA", (max_w, total_h * 3), (0, 0, 0, 0))
  535. y = 0
  536. for text_image, text_data in zip(text_image_list, text_list):
  537. bg = bg.paste_img(top_img=text_image, value=(0, y), base=base)
  538. y += spacing + text_image.height
  539. if "spacing" in text_data:
  540. y += text_data["spacing"]
  541. bg = bg.crop(mode="min")
  542. # _ = bg.paste_img_invert(top_img=PictureProcessing("RGB", (bg.width,bg.height), (255, 255, 255)))
  543. # _.show()
  544. return bg
  545. def generate_font_list_to_pic(self):
  546. font_path_list = [r"resources\ttf\puhui\Bold.ttf",
  547. r"resources\ttf\puhui\Medium.ttf",
  548. r"resources\ttf\puhui\Heavy.ttf",
  549. r"resources\ttf\puhui\Light.ttf",
  550. r"resources\ttf\puhui\Regular.ttf",
  551. ]
  552. text_v_list = [
  553. "这是一段话Bold",
  554. "这是一段话Medium",
  555. "这是一段话Heavy",
  556. "这是一段话Light",
  557. "这是一段话Regular",
  558. ]
  559. detailed_images = []
  560. for font_path, text in zip(font_path_list, text_v_list):
  561. text_list = []
  562. for size in range(26, 80, 2):
  563. font = ImageFont.truetype(font_path, size)
  564. text_list.append({"text": "{}-字号{}".format(text, size),
  565. "font": font,
  566. "fill": (110, 110, 110),
  567. })
  568. text_image = self.add_text_list(text_list, spacing=15, base="nw")
  569. text_image = text_image.crop(mode="min")
  570. text_image = text_image.paste_img_invert(top_img=PictureProcessing("RGB", text_image.size, (255, 255, 255)))
  571. detailed_images.append(text_image)
  572. return PictureProcessing(im=self.add_pic(detailed_images))
  573. # 图片分段,每段至少大于N长度
  574. def pp_pic_subsection(self, pp: PictureProcessing, one_height=3200):
  575. total_height = pp.height
  576. now_height = 0
  577. detailed_images = []
  578. while 1:
  579. if now_height + one_height < total_height:
  580. h1 = now_height
  581. h2 = now_height + one_height
  582. bbox = (0, h1, pp.width, h2)
  583. # print("bbox1", bbox)
  584. detailed_images.append(pp.crop(bbox=bbox))
  585. now_height = now_height + one_height
  586. continue
  587. if now_height + one_height >= total_height:
  588. h1 = now_height
  589. h2 = total_height
  590. bbox = (0, h1, pp.width, h2)
  591. # print("bbox2", bbox)
  592. detailed_images.append(pp.crop(bbox=bbox))
  593. break
  594. return detailed_images