detail_generate_base.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. scp_path = "{out_put_dir}/{goods_no}".format(
  199. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  200. )
  201. if self.get_text_value("模特图"):
  202. model_pic = self.get_text_value("模特图")
  203. self.copyImage(model_pic, f"{scp_path}/模特图.jpg")
  204. if self.get_text_value("场景图"):
  205. scene_pic = self.get_text_value("场景图")
  206. self.copyImage(scene_pic, f"{scp_path}/场景图.jpg")
  207. return True
  208. def copyImage(self,src_path,limit_path):
  209. try:
  210. shutil.copy(src_path, limit_path)
  211. except Exception as e:
  212. print(f'An exception occurred:{e}')
  213. def concatAigcImage(self,image_path,resize=1600,bg_color=(255,255,255)):
  214. """拼接模特图场景图"""
  215. try:
  216. mote_img = PictureProcessing(image_path)
  217. mote_img = mote_img.resize(value=resize)
  218. bg_img = PictureProcessing(
  219. "RGB", (mote_img.width, mote_img.height), bg_color
  220. )
  221. bg_img = bg_img.paste_img(top_img=mote_img, base="nc", value=(0, 0))
  222. return bg_img
  223. except:
  224. print('An exception occurred')
  225. return
  226. # 移动一张图片到新的文件夹
  227. def move_one_pic(self, old_path, new_path, new_name):
  228. image_file = os.listdir(old_path)[0]
  229. old_image_path = "{}/{}".format(old_path, image_file)
  230. image_e = os.path.splitext(image_file)[1]
  231. new_image_path = "{}/{}{}".format(new_path, new_name, image_e)
  232. shutil.copy(old_image_path, new_image_path)
  233. # 生成各个详情图切片
  234. def deal_details(self):
  235. detailed_images = []
  236. for index, func in enumerate(self.deal_pic_func_list):
  237. image_pp = func()
  238. if not self.assigned_page_list:
  239. self.image_list_append(detailed_images, image_pp)
  240. else:
  241. index = "{}".format(index + 1)
  242. if index in self.assigned_page_list:
  243. self.image_list_append(detailed_images, image_pp)
  244. else:
  245. self.image_list_append(detailed_images, {"mes": "不生成"})
  246. return [x for x in detailed_images if x]
  247. # 生成拼接的图片
  248. def generate_spliced_picture(self):
  249. # sendMessageAsync(
  250. # code=0,
  251. # msg="正在生成详情拼接图",
  252. # msg_type="detail_progress",
  253. # data={
  254. # "goods_no": self.goods_no,
  255. # "temp_name": self.template_name,
  256. # "status": "进行中",
  257. # "goods_art_nos": self.goods_art_nos,
  258. # },
  259. # )
  260. detail_path = "{out_put_dir}/{goods_no}/详情页切片".format(
  261. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  262. )
  263. if not os.path.exists(detail_path):
  264. return
  265. detailed_images = []
  266. for image_data in get_images(detail_path):
  267. detailed_images.append(PictureProcessing(image_data["file_path"]))
  268. # 生成拼接图
  269. img = self.add_pic(detailed_images)
  270. join_path = "{out_put_dir}/{goods_no}/详情页".format(
  271. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  272. )
  273. # self.create_folder(join_path)
  274. img.save("{}.jpg".format(join_path), format="JPEG")
  275. def image_list_append(self, image_list: list, data):
  276. self.check_state_end()
  277. if isinstance(data, list):
  278. image_list.extend(data)
  279. else:
  280. image_list.append(data)
  281. def save_to_png(self, detailed_images, detail_path):
  282. self.check_state_end()
  283. for index, pp in enumerate(detailed_images):
  284. if isinstance(pp, dict):
  285. continue
  286. pp.im.save(
  287. "{}/{}({}).png".format(
  288. detail_path, self.goods_no, str(index + 11).zfill(2)
  289. )
  290. )
  291. def check_state_end(self):
  292. if self.windows is not None:
  293. if self.windows.state == 99:
  294. raise "用户主动取消"
  295. @classmethod
  296. def get_temp_pic_info(cls, root):
  297. """
  298. 获取详情页模板中的信息
  299. """
  300. main_pic_list = []
  301. mask_pic_list = []
  302. if os.path.exists(r"{}\main_image".format(root)):
  303. for _name in os.listdir(r"{}\main_image".format(root)):
  304. _path = r"{}\main_image\{}".format(root, _name)
  305. if os.path.isdir(_path):
  306. main_pic_list.append([x["file_path"] for x in get_images(_path)])
  307. mask_pic_list.append(
  308. [x["file_path"] for x in get_image_mask(_path)]
  309. )
  310. _l = get_images(r"{}\show".format(root))
  311. temp_pic_path = _l[0]["file_path"] if _l else None
  312. other_pic_list = [x["file_path"] for x in get_images(r"{}".format(root))]
  313. return {
  314. "main_pic_path_list": main_pic_list,
  315. "temp_pic_path": temp_pic_path,
  316. "mask_pic_list": mask_pic_list,
  317. "other_pic_path_list": other_pic_list,
  318. }
  319. def init(self):
  320. for goods_art_no_value in self.goods_no_value["货号资料"]:
  321. self.data[goods_art_no_value["货号"]] = {
  322. "pics": goods_art_no_value["pics"],
  323. "pic_is_deal": {},
  324. }
  325. def get_text_value(self, key, subsection_len=0):
  326. text = ""
  327. if key in self.goods_no_value:
  328. if self.goods_no_value[key]:
  329. text = str(self.goods_no_value[key])
  330. text = text.replace(r"\n", "\n")
  331. # if key in ["跟高", "鞋宽", "帮高", "脚掌围", "鞋长"]:
  332. # if text:
  333. # text = text.split(".")[0]
  334. if subsection_len != 0:
  335. text = text.split("\n")
  336. text = [x for x in text if x]
  337. if len(text) == 2:
  338. text_1 = text[0]
  339. text_2 = text[1]
  340. return text_1, text_2
  341. else:
  342. if text:
  343. text_1 = text[0]
  344. else:
  345. text_1 = ""
  346. text_2 = ""
  347. return text_1, text_2
  348. return text
  349. def create_folder(self, path):
  350. if not os.path.exists(path):
  351. os.makedirs(path)
  352. def get_all_process_pics(self):
  353. """
  354. 获取所有颜色的过程图片
  355. data = [
  356. {"货号": "",
  357. "素材": [{
  358. "名称": "俯视",
  359. "抠图": "路径1",
  360. "阴影": "路径2"
  361. }, ]},
  362. ]
  363. """
  364. return_data = []
  365. for goods_art_no in self.data:
  366. goods_art_no_dict = {
  367. "货号": goods_art_no,
  368. "素材": [],
  369. }
  370. # 图片数据重新排序
  371. pic_data = []
  372. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  373. root_path, file_name = os.path.split(pic_path)
  374. pic_data.append(file_name)
  375. pic_data = natsorted(pic_data, alg=ns.PATH)
  376. for file_name in pic_data:
  377. if "阴影" in file_name:
  378. _, action_name, _ = file_name.split("_")
  379. pic_path = self.data[goods_art_no]["pics"][
  380. "{}-阴影".format(action_name)
  381. ]
  382. pic_cutout_path = self.data[goods_art_no]["pics"][
  383. "{}-抠图".format(action_name)
  384. ]
  385. if os.path.exists(pic_path) and os.path.exists(pic_cutout_path):
  386. goods_art_no_dict["素材"].append(
  387. {
  388. "名称": action_name,
  389. "抠图": pic_cutout_path,
  390. "阴影": pic_path,
  391. }
  392. )
  393. return_data.append(goods_art_no_dict)
  394. return return_data
  395. def get_overlay_pic_from_dict(
  396. self, goods_art_no, color_name, bg_color
  397. ) -> PictureProcessing:
  398. self.check_state_end()
  399. # 增加逻辑,获取任意货号下的组合图
  400. if "组合" in color_name:
  401. goods_art_no, color_name = self.get_all_scene_list(goods_art_no, color_name)
  402. key = "{}-{}-{}".format(goods_art_no, color_name, bg_color)
  403. if key in self.overlay_pic_dict:
  404. return self.overlay_pic_dict[key]
  405. if goods_art_no in self.data:
  406. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  407. if "阴影" in pic_name:
  408. action_name = pic_name.replace("-阴影", "")
  409. if action_name == color_name:
  410. pp1 = PictureProcessing(pic_path)
  411. pp2 = PictureProcessing(
  412. self.data[goods_art_no]["pics"][
  413. "{}-抠图".format(action_name)
  414. ]
  415. )
  416. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  417. mode="pixel", base="width", value=1600
  418. )
  419. self.overlay_pic_dict[key] = pp1
  420. if key in self.overlay_pic_dict:
  421. return self.overlay_pic_dict[key]
  422. def image_init(self, bg_color=(246, 246, 246)):
  423. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  424. for goods_art_no in self.data:
  425. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  426. if "阴影" in pic_name:
  427. action_name = pic_name.replace("-阴影", "")
  428. pp1 = PictureProcessing(pic_path)
  429. pp2 = PictureProcessing(
  430. self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)]
  431. )
  432. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  433. mode="pixel", base="width", value=1600
  434. )
  435. self.data[goods_art_no]["pic_is_deal"][action_name] = pp1
  436. # 获取任意货号的场景图,优先取指定货号;
  437. # 调整,按顺序从货号列表中提取所有组合图
  438. def get_all_scene_info(self, goods_art_no):
  439. data = []
  440. # 收集所有组合图
  441. # 找任意一个有组合图的货号
  442. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  443. _goods_art_no = goods_art_no_dict["货号"]
  444. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  445. for _view_name in _view_name_list:
  446. if "组合" not in _view_name:
  447. continue
  448. return _goods_art_no
  449. return goods_art_no
  450. def get_all_scene_list(self, goods_art_no, view_name: str):
  451. if "组合" == view_name:
  452. view_name = "组合1"
  453. try:
  454. view_index = int(view_name.replace("组合", "")) - 1
  455. except:
  456. return goods_art_no, "无法匹配"
  457. data = []
  458. # 收集所有组合图
  459. # 找任意一个有组合图的货号
  460. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  461. _goods_art_no = goods_art_no_dict["货号"]
  462. if _goods_art_no != goods_art_no:
  463. continue
  464. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  465. for _view_name in _view_name_list:
  466. if "组合" not in _view_name:
  467. continue
  468. data.append(
  469. {
  470. "goods_art_no": _goods_art_no,
  471. "view_name": _view_name,
  472. "real_view_name": (
  473. "组合1" if _view_name == "组合" else _view_name
  474. ),
  475. }
  476. )
  477. if len(data) <= view_index:
  478. return goods_art_no, "无法匹配"
  479. else:
  480. data.sort(key=lambda x: x["real_view_name"], reverse=False)
  481. return data[view_index]["goods_art_no"], data[view_index]["view_name"]
  482. def image_one_pic(self, goods_art_no, name, bg_color=None, return_orign=None):
  483. # 增加逻辑,获取任意货号下的组合图
  484. if "组合" in name:
  485. print("324==== goods_art_no, name", goods_art_no, name)
  486. goods_art_no, name = self.get_all_scene_list(goods_art_no, name)
  487. print("324 goods_art_no, name", goods_art_no, name)
  488. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  489. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  490. if "阴影" in pic_name:
  491. action_name = pic_name.replace("-阴影", "")
  492. if name != action_name:
  493. continue
  494. pp1 = PictureProcessing(pic_path)
  495. pp2 = PictureProcessing(
  496. self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)]
  497. )
  498. if not return_orign:
  499. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  500. mode="pixel", base="width", value=1600
  501. )
  502. return pp1
  503. else:
  504. return pp1, pp2
  505. if not return_orign:
  506. return None
  507. else:
  508. return None, None
  509. def move_other_pic(self, move_main_pic=True):
  510. # ------------------------------移动其他图片------------------------------
  511. goods_no_main_pic_number = 0
  512. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  513. if "800x800" not in goods_art_no_dict:
  514. continue
  515. if not goods_art_no_dict["800x800"]:
  516. continue
  517. goods_art_no = ""
  518. if "编号" in goods_art_no_dict:
  519. if goods_art_no_dict["编号"]:
  520. goods_art_no = goods_art_no_dict["编号"]
  521. if not goods_art_no:
  522. goods_art_no = goods_art_no_dict["货号"]
  523. # print("goods_art_no:", goods_art_no)
  524. # 移动颜色图=====================
  525. goods_art_no_f = "{}/{}".format(self.out_put_dir, self.goods_no)
  526. self.create_folder(goods_art_no_f)
  527. # 放入一张主图
  528. old_pic_path_1 = goods_art_no_dict["800x800"][0]
  529. shutil.copy(
  530. old_pic_path_1,
  531. "{}/颜色图{}{}".format(
  532. goods_art_no_f, goods_art_no, os.path.splitext(old_pic_path_1)[1]
  533. ),
  534. )
  535. # 把其他主图放入作为款号图=====================
  536. if move_main_pic:
  537. for pic_path in goods_art_no_dict["800x800"]:
  538. goods_no_main_pic_number += 1
  539. e = os.path.splitext(pic_path)[1]
  540. shutil.copy(
  541. pic_path,
  542. "{out_put_dir}/{goods_no}/主图{goods_no}({goods_no_main_pic_number}){e}".format(
  543. out_put_dir=self.out_put_dir,
  544. goods_no=self.goods_no,
  545. goods_no_main_pic_number=str(
  546. goods_no_main_pic_number + 10
  547. ).zfill(2),
  548. e=e,
  549. ),
  550. )
  551. def deal_all_main_pic(self):
  552. """
  553. 处理主图模板,如存在出图模板则进行对应处理
  554. """
  555. # 获取主图模板列表
  556. all_main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)[
  557. "main_pic_path_list"
  558. ]
  559. if not all_main_pic_path_list:
  560. return
  561. mask_pic_list = DetailBase.get_temp_pic_info(root=self.root)["mask_pic_list"]
  562. data = self.get_all_process_pics()
  563. print("========deal_all_main_pic=========主图相关素材:")
  564. view_list = [
  565. "组合",
  566. "组合2",
  567. "组合3",
  568. "组合4",
  569. "组合5",
  570. "组合6",
  571. "俯视",
  572. "侧视",
  573. "后跟",
  574. "鞋底",
  575. "内里",
  576. ]
  577. for _index, main_pic_path_list in enumerate(all_main_pic_path_list):
  578. self.check_state_end()
  579. out_path_root = "{out_put_dir}/{goods_no}/main_image_{_index}".format(
  580. out_put_dir=self.out_put_dir, goods_no=self.goods_no, _index=_index
  581. )
  582. check_path(out_path_root)
  583. if mask_pic_list[_index]:
  584. mask_pic = mask_pic_list[_index][0]
  585. else:
  586. mask_pic = None
  587. goods_no_main_pic_number = 10
  588. # g_index 为第几个颜色货号
  589. for g_index, goods_art_no_dict in enumerate(data):
  590. goods_art_no = goods_art_no_dict["货号"]
  591. # =====================重新指定=================================
  592. _material_sort_dict = {}
  593. for index, material_dict in enumerate(goods_art_no_dict["素材"]):
  594. name = material_dict["名称"]
  595. _material_sort_dict[name] = material_dict
  596. # ======================================================
  597. file_name_index = -1
  598. for view_name in view_list:
  599. # 组合图比较特殊,为全局获取
  600. if g_index != 0:
  601. if "组合" in view_name:
  602. continue
  603. if view_name not in _material_sort_dict:
  604. continue
  605. self.check_state_end()
  606. pp_jpg, pp_png = self.image_one_pic(
  607. goods_art_no, view_name, bg_color=None, return_orign=True
  608. )
  609. if not pp_jpg:
  610. continue
  611. file_name_index += 1
  612. # 获取对应主图模板
  613. if len(main_pic_path_list) < file_name_index + 1:
  614. main_pic_path = main_pic_path_list[-1]
  615. else:
  616. main_pic_path = main_pic_path_list[file_name_index]
  617. pp_bg = PictureProcessing(main_pic_path)
  618. original_width = pp_bg.width
  619. if original_width != 1600:
  620. pp_bg = pp_bg.resize(value=1600)
  621. if mask_pic:
  622. mask_bg = PictureProcessing(mask_pic)
  623. mask_bg = mask_bg.resize(value=1600)
  624. mask_box_im = mask_bg.get_im()
  625. box_size = mask_box_im.getbbox()
  626. result_image = mask_box_im.crop(box_size)
  627. mask_width, mask_height = result_image.size
  628. mask_x, mask_y = box_size[0], box_size[1]
  629. else:
  630. mask_width, mask_height = pp_bg.size
  631. mask_width, mask_height = int(mask_width * 12 / 16), int(
  632. mask_height * 12 / 16
  633. )
  634. mask_x, mask_y = int((pp_bg.size[0] - mask_width) / 2), int(
  635. (pp_bg.size[1] - mask_height) / 2
  636. )
  637. if view_name != "后跟":
  638. pp_jpg = pp_jpg.resize(base_by_box=(mask_width, mask_height))
  639. pp_png = pp_png.resize(base_by_box=(mask_width, mask_height))
  640. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  641. p_x = mask_x + int((mask_width - pp_jpg.width) / 2)
  642. p_y = mask_y + int((mask_height - pp_jpg.height) / 2)
  643. pp_bg = pp_bg.to_overlay_pic_advance(
  644. mode="pixel",
  645. top_img=pp_jpg,
  646. base="nw",
  647. value=(p_x, p_y),
  648. top_png_img=pp_png,
  649. )
  650. else:
  651. new_mask_width, new_mask_height = int(mask_width / 1.6), int(
  652. mask_height / 1.6
  653. )
  654. pp_jpg = pp_jpg.resize(
  655. base_by_box=(new_mask_width, new_mask_height)
  656. )
  657. pp_png = pp_png.resize(
  658. base_by_box=(new_mask_width, new_mask_height)
  659. )
  660. new_mask_x = int((mask_width - new_mask_width) / 2 + mask_x)
  661. new_mask_y = int((mask_height - new_mask_height) / 2 + mask_y)
  662. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  663. p_x = new_mask_x + int((new_mask_width - pp_jpg.width) / 2)
  664. p_y = new_mask_y + int((new_mask_height - pp_jpg.height) / 2)
  665. pp_bg = pp_bg.to_overlay_pic_advance(
  666. mode="pixel",
  667. top_img=pp_jpg,
  668. base="nw",
  669. value=(p_x, p_y),
  670. top_png_img=pp_png,
  671. )
  672. out_pci_mode = "." + settings.getSysConfigs(
  673. "basic_configs", "image_out_format", "png"
  674. )
  675. goods_no_main_pic_number += 1
  676. out_pic_path = "{out_path_root}/{goods_no}({goods_no_main_pic_number}){pic_mode}".format(
  677. out_path_root=out_path_root,
  678. goods_no=self.goods_no,
  679. goods_no_main_pic_number=goods_no_main_pic_number,
  680. pic_mode=out_pci_mode,
  681. )
  682. out_pci_factor = float(
  683. 1
  684. if settings.getSysConfigs(
  685. "basic_configs", "image_sharpening", "1"
  686. )
  687. == ""
  688. else settings.getSysConfigs(
  689. "basic_configs", "image_sharpening", "1"
  690. )
  691. )
  692. if out_pci_factor > 1.0:
  693. print("图片锐化处理")
  694. pp_bg = pp_bg.sharpen_image(factor=out_pci_factor)
  695. if original_width < 1600:
  696. pp_bg = pp_bg.resize(value=original_width)
  697. print("392 out_pic_path", out_pic_path)
  698. if out_pci_mode == ".jpg":
  699. pp_bg.save_as_rgb(out_pic_path)
  700. elif out_pci_mode == ".png":
  701. pp_bg.save_as_png(out_pic_path)
  702. else:
  703. pp_bg.save_as_other(out_pic_path, out_pci_mode.split(".")[-1])
  704. def add_pic(self, detailed_images):
  705. self.check_state_end()
  706. todo_detailed_images = []
  707. detailed_images = [x for x in detailed_images if x]
  708. if not detailed_images:
  709. return
  710. for i in detailed_images:
  711. if isinstance(i, list):
  712. for n in i:
  713. todo_detailed_images.append(n)
  714. else:
  715. todo_detailed_images.append(i)
  716. page_len = 0
  717. for index, pp in enumerate(todo_detailed_images):
  718. page_len += pp.height
  719. bg_im = Image.new("RGB", (pp.width, page_len), (255, 255, 255))
  720. n = 0
  721. for index, pp in enumerate(todo_detailed_images):
  722. bg_im.paste(pp.im, (0, n))
  723. n += pp.height
  724. return bg_im
  725. # 通用方法,用于写文字
  726. def add_text_list(self, text_list, spacing=5, base="wn", base_width=1600):
  727. text_list = [x for x in text_list if x["text"]]
  728. # print(text_list)
  729. # spacing 行间距
  730. text_image_list = []
  731. max_w = 0
  732. total_h = 0
  733. for text_data in text_list:
  734. _pp = PictureProcessing("RGBA", (base_width, 1200), (255, 255, 255, 0))
  735. if base == "wn" or base == "nw":
  736. align = "left"
  737. anchor = None
  738. value = (0, 250)
  739. if base == "cn" or base == "nc":
  740. align = "center"
  741. anchor = "mm"
  742. value = (int(base_width / 2), 250)
  743. if base == "en" or base == "ne":
  744. align = "right"
  745. anchor = "rs"
  746. value = (base_width - 10, 250)
  747. _pp = _pp.get_text_image_advanced(
  748. value=value,
  749. font=text_data["font"],
  750. text=text_data["text"],
  751. align=align,
  752. anchor=anchor,
  753. spacing=5,
  754. fill=text_data["fill"],
  755. return_mode="min_image",
  756. margins=(0, 0, 0, 0),
  757. )
  758. text_image_list.append(_pp)
  759. if _pp.width > max_w:
  760. max_w = _pp.width
  761. total_h += _pp.height
  762. if "spacing" in text_data:
  763. total_h += text_data["spacing"]
  764. if not text_image_list:
  765. return None
  766. #
  767. bg = PictureProcessing("RGBA", (max_w, total_h * 3), (0, 0, 0, 0))
  768. y = 0
  769. for text_image, text_data in zip(text_image_list, text_list):
  770. bg = bg.paste_img(top_img=text_image, value=(0, y), base=base)
  771. y += spacing + text_image.height
  772. if "spacing" in text_data:
  773. y += text_data["spacing"]
  774. bg = bg.crop(mode="min")
  775. # _ = bg.paste_img_invert(top_img=PictureProcessing("RGB", (bg.width,bg.height), (255, 255, 255)))
  776. # _.show()
  777. return bg
  778. def generate_font_list_to_pic(self):
  779. font_path_list = [
  780. r"resources\ttf\puhui\Bold.ttf",
  781. r"resources\ttf\puhui\Medium.ttf",
  782. r"resources\ttf\puhui\Heavy.ttf",
  783. r"resources\ttf\puhui\Light.ttf",
  784. r"resources\ttf\puhui\Regular.ttf",
  785. ]
  786. text_v_list = [
  787. "这是一段话Bold",
  788. "这是一段话Medium",
  789. "这是一段话Heavy",
  790. "这是一段话Light",
  791. "这是一段话Regular",
  792. ]
  793. detailed_images = []
  794. for font_path, text in zip(font_path_list, text_v_list):
  795. text_list = []
  796. for size in range(26, 80, 2):
  797. font = ImageFont.truetype(font_path, size)
  798. text_list.append(
  799. {
  800. "text": "{}-字号{}".format(text, size),
  801. "font": font,
  802. "fill": (110, 110, 110),
  803. }
  804. )
  805. text_image = self.add_text_list(text_list, spacing=15, base="nw")
  806. text_image = text_image.crop(mode="min")
  807. text_image = text_image.paste_img_invert(
  808. top_img=PictureProcessing("RGB", text_image.size, (255, 255, 255))
  809. )
  810. detailed_images.append(text_image)
  811. return PictureProcessing(im=self.add_pic(detailed_images))
  812. # 图片分段,每段至少大于N长度
  813. def pp_pic_subsection(self, pp: PictureProcessing, one_height=3200):
  814. total_height = pp.height
  815. now_height = 0
  816. detailed_images = []
  817. while 1:
  818. if now_height + one_height < total_height:
  819. h1 = now_height
  820. h2 = now_height + one_height
  821. bbox = (0, h1, pp.width, h2)
  822. # print("bbox1", bbox)
  823. detailed_images.append(pp.crop(bbox=bbox))
  824. now_height = now_height + one_height
  825. continue
  826. if now_height + one_height >= total_height:
  827. h1 = now_height
  828. h2 = total_height
  829. bbox = (0, h1, pp.width, h2)
  830. # print("bbox2", bbox)
  831. detailed_images.append(pp.crop(bbox=bbox))
  832. break
  833. return detailed_images