detail_generate_base.py 35 KB

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