detail_generate_base.py 33 KB

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