detail_generate_base.py 30 KB

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