detail_generate_base.py 35 KB

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