detail_generate_base.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. }
  304. )
  305. if len(data) <= view_index:
  306. return goods_art_no, "无法匹配"
  307. else:
  308. return data[view_index]["goods_art_no"], data[view_index]["view_name"]
  309. def image_one_pic(self, goods_art_no, name, bg_color=None, return_orign=None):
  310. # 增加逻辑,获取任意货号下的组合图
  311. if "组合" in name:
  312. goods_art_no, name = self.get_all_scene_list(goods_art_no, name)
  313. print("324 goods_art_no, name", goods_art_no, name)
  314. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  315. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  316. if "阴影" in pic_name:
  317. action_name = pic_name.replace("-阴影", "")
  318. if name != action_name:
  319. continue
  320. pp1 = PictureProcessing(pic_path)
  321. pp2 = PictureProcessing(self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)])
  322. if not return_orign:
  323. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(mode="pixel", base="width",
  324. value=1600)
  325. return pp1
  326. else:
  327. return pp1, pp2
  328. if not return_orign:
  329. return None
  330. else:
  331. return None, None
  332. def move_other_pic(self, move_main_pic=True):
  333. # ------------------------------移动其他图片------------------------------
  334. goods_no_main_pic_number = 0
  335. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  336. if "800x800" not in goods_art_no_dict:
  337. continue
  338. if not goods_art_no_dict["800x800"]:
  339. continue
  340. goods_art_no = ""
  341. if "编号" in goods_art_no_dict:
  342. if goods_art_no_dict["编号"]:
  343. goods_art_no = goods_art_no_dict["编号"]
  344. if not goods_art_no:
  345. goods_art_no = goods_art_no_dict["货号"]
  346. # print("goods_art_no:", goods_art_no)
  347. # 移动颜色图=====================
  348. goods_art_no_f = "{}/{}/{}".format(self.out_put_dir, self.goods_no, goods_art_no)
  349. self.create_folder(goods_art_no_f)
  350. # 放入一张主图
  351. old_pic_path_1 = goods_art_no_dict["800x800"][0]
  352. shutil.copy(old_pic_path_1,
  353. "{}/{}{}".format(goods_art_no_f, goods_art_no, os.path.splitext(old_pic_path_1)[1]))
  354. # 把其他主图放入作为款号图=====================
  355. if move_main_pic:
  356. for pic_path in goods_art_no_dict["800x800"]:
  357. goods_no_main_pic_number += 1
  358. e = os.path.splitext(pic_path)[1]
  359. shutil.copy(pic_path,
  360. "{out_put_dir}/{goods_no}/{goods_no}({goods_no_main_pic_number}){e}".format(
  361. out_put_dir=self.out_put_dir, goods_no=self.goods_no,
  362. goods_no_main_pic_number=str(goods_no_main_pic_number + 10).zfill(2),
  363. e=e))
  364. def deal_all_main_pic(self):
  365. """
  366. 处理主图模板,如存在出图模板则进行对应处理
  367. """
  368. # 获取主图模板列表
  369. all_main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)["main_pic_path_list"]
  370. if not all_main_pic_path_list:
  371. return
  372. mask_pic_list = DetailBase.get_temp_pic_info(root=self.root)["mask_pic_list"]
  373. data = self.get_all_process_pics()
  374. print("========deal_all_main_pic=========主图相关素材:")
  375. view_list = ["组合", "组合2", "组合3", "组合4", "组合5", "组合6", "俯视", "侧视", "后跟", "鞋底", "内里", ]
  376. for _index, main_pic_path_list in enumerate(all_main_pic_path_list):
  377. self.check_state_end()
  378. out_path_root = "{out_put_dir}/{goods_no}/main_image_{_index}".format(
  379. out_put_dir=self.out_put_dir,
  380. goods_no=self.goods_no,
  381. _index=_index
  382. )
  383. check_path(out_path_root)
  384. if mask_pic_list[_index]:
  385. mask_pic = mask_pic_list[_index][0]
  386. else:
  387. mask_pic = None
  388. goods_no_main_pic_number = 10
  389. # g_index 为第几个颜色货号
  390. for g_index, goods_art_no_dict in enumerate(data):
  391. goods_art_no = goods_art_no_dict["货号"]
  392. # =====================重新指定=================================
  393. _material_sort_dict = {}
  394. for index, material_dict in enumerate(goods_art_no_dict["素材"]):
  395. name = material_dict["名称"]
  396. _material_sort_dict[name] = material_dict
  397. # ======================================================
  398. file_name_index = -1
  399. for view_name in view_list:
  400. # 组合图比较特殊,为全局获取
  401. if g_index != 0:
  402. if "组合" in view_name:
  403. continue
  404. if view_name not in _material_sort_dict:
  405. continue
  406. self.check_state_end()
  407. pp_jpg, pp_png = self.image_one_pic(goods_art_no, view_name, bg_color=None, return_orign=True)
  408. if not pp_jpg:
  409. continue
  410. file_name_index += 1
  411. # 获取对应主图模板
  412. if len(main_pic_path_list) < file_name_index + 1:
  413. main_pic_path = main_pic_path_list[-1]
  414. else:
  415. main_pic_path = main_pic_path_list[file_name_index]
  416. pp_bg = PictureProcessing(main_pic_path)
  417. original_width = pp_bg.width
  418. if original_width != 1600:
  419. pp_bg = pp_bg.resize(value=1600)
  420. if mask_pic:
  421. mask_bg = PictureProcessing(mask_pic)
  422. mask_bg = mask_bg.resize(value=1600)
  423. mask_box_im = mask_bg.get_im()
  424. box_size = mask_box_im.getbbox()
  425. result_image = mask_box_im.crop(box_size)
  426. mask_width, mask_height = result_image.size
  427. mask_x, mask_y = box_size[0], box_size[1]
  428. else:
  429. mask_width, mask_height = pp_bg.size
  430. mask_width, mask_height = int(mask_width * 12 / 16), int(mask_height * 12 / 16)
  431. mask_x, mask_y = int((pp_bg.size[0] - mask_width) / 2), int((pp_bg.size[1] - mask_height) / 2)
  432. if view_name != "后跟":
  433. pp_jpg = pp_jpg.resize(base_by_box=(mask_width, mask_height))
  434. pp_png = pp_png.resize(base_by_box=(mask_width, mask_height))
  435. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  436. p_x = mask_x + int((mask_width - pp_jpg.width) / 2)
  437. p_y = mask_y + int((mask_height - pp_jpg.height) / 2)
  438. pp_bg = pp_bg.to_overlay_pic_advance(mode="pixel", top_img=pp_jpg, base="nw",
  439. value=(p_x, p_y), top_png_img=pp_png)
  440. else:
  441. new_mask_width, new_mask_height = int(mask_width / 1.6), int(mask_height / 1.6)
  442. pp_jpg = pp_jpg.resize(base_by_box=(new_mask_width, new_mask_height))
  443. pp_png = pp_png.resize(base_by_box=(new_mask_width, new_mask_height))
  444. new_mask_x = int((mask_width - new_mask_width) / 2 + mask_x)
  445. new_mask_y = int((mask_height - new_mask_height) / 2 + mask_y)
  446. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  447. p_x = new_mask_x + int((new_mask_width - pp_jpg.width) / 2)
  448. p_y = new_mask_y + int((new_mask_height - pp_jpg.height) / 2)
  449. pp_bg = pp_bg.to_overlay_pic_advance(mode="pixel", top_img=pp_jpg, base="nw", value=(p_x, p_y),
  450. top_png_img=pp_png)
  451. goods_no_main_pic_number += 1
  452. out_pic_path = "{out_path_root}/{goods_no}({goods_no_main_pic_number}){pic_mode}".format(
  453. out_path_root=out_path_root,
  454. goods_no=self.goods_no,
  455. goods_no_main_pic_number=goods_no_main_pic_number,
  456. pic_mode=settings.OUT_PIC_MODE,
  457. )
  458. if settings.OUT_PIC_FACTOR > 1.0:
  459. print("图片锐化处理")
  460. pp_bg = pp_bg.sharpen_image(factor=settings.OUT_PIC_FACTOR)
  461. if original_width < 1600:
  462. pp_bg = pp_bg.resize(value=original_width)
  463. print("392 out_pic_path", out_pic_path)
  464. if settings.OUT_PIC_MODE == ".jpg":
  465. pp_bg.save_as_rgb(out_pic_path)
  466. else:
  467. pp_bg.save_as_png(out_pic_path)
  468. def add_pic(self, detailed_images):
  469. self.check_state_end()
  470. todo_detailed_images = []
  471. detailed_images = [x for x in detailed_images if x]
  472. if not detailed_images:
  473. return
  474. for i in detailed_images:
  475. if isinstance(i, list):
  476. for n in i:
  477. todo_detailed_images.append(n)
  478. else:
  479. todo_detailed_images.append(i)
  480. page_len = 0
  481. for index, pp in enumerate(todo_detailed_images):
  482. page_len += pp.height
  483. bg_im = Image.new("RGB", (pp.width, page_len), (255, 255, 255))
  484. n = 0
  485. for index, pp in enumerate(todo_detailed_images):
  486. bg_im.paste(pp.im, (0, n))
  487. n += pp.height
  488. return bg_im
  489. # 通用方法,用于写文字
  490. def add_text_list(self, text_list, spacing=5, base="wn", base_width=1600):
  491. text_list = [x for x in text_list if x["text"]]
  492. # print(text_list)
  493. # spacing 行间距
  494. text_image_list = []
  495. max_w = 0
  496. total_h = 0
  497. for text_data in text_list:
  498. _pp = PictureProcessing("RGBA", (base_width, 1200), (255, 255, 255, 0))
  499. if base == "wn" or base == "nw":
  500. align = "left"
  501. anchor = None
  502. value = (0, 250)
  503. if base == "cn" or base == "nc":
  504. align = "center"
  505. anchor = "mm"
  506. value = (int(base_width / 2), 250)
  507. if base == "en" or base == "ne":
  508. align = "right"
  509. anchor = "rs"
  510. value = (base_width - 10, 250)
  511. _pp = _pp.get_text_image_advanced(
  512. value=value,
  513. font=text_data["font"],
  514. text=text_data["text"],
  515. align=align,
  516. anchor=anchor,
  517. spacing=5,
  518. fill=text_data["fill"],
  519. return_mode="min_image",
  520. margins=(0, 0, 0, 0)
  521. )
  522. text_image_list.append(_pp)
  523. if _pp.width > max_w:
  524. max_w = _pp.width
  525. total_h += _pp.height
  526. if "spacing" in text_data:
  527. total_h += text_data["spacing"]
  528. if not text_image_list:
  529. return None
  530. #
  531. bg = PictureProcessing("RGBA", (max_w, total_h * 3), (0, 0, 0, 0))
  532. y = 0
  533. for text_image, text_data in zip(text_image_list, text_list):
  534. bg = bg.paste_img(top_img=text_image, value=(0, y), base=base)
  535. y += spacing + text_image.height
  536. if "spacing" in text_data:
  537. y += text_data["spacing"]
  538. bg = bg.crop(mode="min")
  539. # _ = bg.paste_img_invert(top_img=PictureProcessing("RGB", (bg.width,bg.height), (255, 255, 255)))
  540. # _.show()
  541. return bg
  542. def generate_font_list_to_pic(self):
  543. font_path_list = [r"resources\ttf\puhui\Bold.ttf",
  544. r"resources\ttf\puhui\Medium.ttf",
  545. r"resources\ttf\puhui\Heavy.ttf",
  546. r"resources\ttf\puhui\Light.ttf",
  547. r"resources\ttf\puhui\Regular.ttf",
  548. ]
  549. text_v_list = [
  550. "这是一段话Bold",
  551. "这是一段话Medium",
  552. "这是一段话Heavy",
  553. "这是一段话Light",
  554. "这是一段话Regular",
  555. ]
  556. detailed_images = []
  557. for font_path, text in zip(font_path_list, text_v_list):
  558. text_list = []
  559. for size in range(26, 80, 2):
  560. font = ImageFont.truetype(font_path, size)
  561. text_list.append({"text": "{}-字号{}".format(text, size),
  562. "font": font,
  563. "fill": (110, 110, 110),
  564. })
  565. text_image = self.add_text_list(text_list, spacing=15, base="nw")
  566. text_image = text_image.crop(mode="min")
  567. text_image = text_image.paste_img_invert(top_img=PictureProcessing("RGB", text_image.size, (255, 255, 255)))
  568. detailed_images.append(text_image)
  569. return PictureProcessing(im=self.add_pic(detailed_images))
  570. # 图片分段,每段至少大于N长度
  571. def pp_pic_subsection(self, pp: PictureProcessing, one_height=3200):
  572. total_height = pp.height
  573. now_height = 0
  574. detailed_images = []
  575. while 1:
  576. if now_height + one_height < total_height:
  577. h1 = now_height
  578. h2 = now_height + one_height
  579. bbox = (0, h1, pp.width, h2)
  580. # print("bbox1", bbox)
  581. detailed_images.append(pp.crop(bbox=bbox))
  582. now_height = now_height + one_height
  583. continue
  584. if now_height + one_height >= total_height:
  585. h1 = now_height
  586. h2 = total_height
  587. bbox = (0, h1, pp.width, h2)
  588. # print("bbox2", bbox)
  589. detailed_images.append(pp.crop(bbox=bbox))
  590. break
  591. return detailed_images