detail_generate_base.py 32 KB

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