detail_generate_base.py 30 KB

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