detail_generate_base.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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 image_one_pic_no_shandow(self, goods_art_no, name, bg_color=None, return_orign=None):
  512. # 增加逻辑,获取任意货号下的组合图
  513. if "组合" in name:
  514. print("324==== goods_art_no, name", goods_art_no, name)
  515. goods_art_no, name = self.get_all_scene_list(goods_art_no, name)
  516. print("324 goods_art_no, name", goods_art_no, name)
  517. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  518. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  519. if "抠图" in pic_name:
  520. action_name = pic_name.replace("-抠图", "")
  521. if name != action_name:
  522. continue
  523. colorMode = "RGB"
  524. if bg_color == None:
  525. bg_color = (255,255,255)
  526. img = Image.open(pic_path)
  527. imgBg = Image.new(colorMode, img.size, bg_color)
  528. imgBg.paste(img, (0, 0), img) # 修复:不再将paste()的结果赋值给img
  529. pp1 = PictureProcessing()
  530. pp2 = PictureProcessing()
  531. pp1.im = imgBg
  532. pp2.im = imgBg
  533. return pp1, pp2
  534. if not return_orign:
  535. return None
  536. else:
  537. return None, None
  538. def move_other_pic(self, move_main_pic=True):
  539. # ------------------------------移动其他图片------------------------------
  540. goods_no_main_pic_number = 0
  541. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  542. if "800x800" not in goods_art_no_dict:
  543. continue
  544. if not goods_art_no_dict["800x800"]:
  545. continue
  546. goods_art_no = ""
  547. if "编号" in goods_art_no_dict:
  548. if goods_art_no_dict["编号"]:
  549. goods_art_no = goods_art_no_dict["编号"]
  550. if not goods_art_no:
  551. goods_art_no = goods_art_no_dict["货号"]
  552. # print("goods_art_no:", goods_art_no)
  553. # 移动颜色图=====================
  554. goods_art_no_f = "{}/{}".format(self.out_put_dir, self.goods_no)
  555. self.create_folder(goods_art_no_f)
  556. # 放入一张主图
  557. old_pic_path_1 = goods_art_no_dict["800x800"][0]
  558. shutil.copy(
  559. old_pic_path_1,
  560. "{}/颜色图{}{}".format(
  561. goods_art_no_f, goods_art_no, os.path.splitext(old_pic_path_1)[1]
  562. ),
  563. )
  564. # 把其他主图放入作为款号图=====================
  565. if move_main_pic:
  566. for pic_path in goods_art_no_dict["800x800"]:
  567. goods_no_main_pic_number += 1
  568. e = os.path.splitext(pic_path)[1]
  569. shutil.copy(
  570. pic_path,
  571. "{out_put_dir}/{goods_no}/主图{goods_no}({goods_no_main_pic_number}){e}".format(
  572. out_put_dir=self.out_put_dir,
  573. goods_no=self.goods_no,
  574. goods_no_main_pic_number=str(
  575. goods_no_main_pic_number + 10
  576. ).zfill(2),
  577. e=e,
  578. ),
  579. )
  580. def deal_all_main_pic(self):
  581. """
  582. 处理主图模板,如存在出图模板则进行对应处理
  583. """
  584. # 获取主图模板列表
  585. all_main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)[
  586. "main_pic_path_list"
  587. ]
  588. if not all_main_pic_path_list:
  589. return
  590. mask_pic_list = DetailBase.get_temp_pic_info(root=self.root)["mask_pic_list"]
  591. data = self.get_all_process_pics()
  592. print("========deal_all_main_pic=========主图相关素材:")
  593. view_list = [
  594. "组合",
  595. "组合2",
  596. "组合3",
  597. "组合4",
  598. "组合5",
  599. "组合6",
  600. "俯视",
  601. "侧视",
  602. "后跟",
  603. "鞋底",
  604. "内里",
  605. ]
  606. for _index, main_pic_path_list in enumerate(all_main_pic_path_list):
  607. self.check_state_end()
  608. out_path_root = "{out_put_dir}/{goods_no}/main_image_{_index}".format(
  609. out_put_dir=self.out_put_dir, goods_no=self.goods_no, _index=_index
  610. )
  611. check_path(out_path_root)
  612. if mask_pic_list[_index]:
  613. mask_pic = mask_pic_list[_index][0]
  614. else:
  615. mask_pic = None
  616. goods_no_main_pic_number = 10
  617. # g_index 为第几个颜色货号
  618. for g_index, goods_art_no_dict in enumerate(data):
  619. goods_art_no = goods_art_no_dict["货号"]
  620. # =====================重新指定=================================
  621. _material_sort_dict = {}
  622. for index, material_dict in enumerate(goods_art_no_dict["素材"]):
  623. name = material_dict["名称"]
  624. _material_sort_dict[name] = material_dict
  625. # ======================================================
  626. file_name_index = -1
  627. for view_name in view_list:
  628. # 组合图比较特殊,为全局获取
  629. if g_index != 0:
  630. if "组合" in view_name:
  631. continue
  632. if view_name not in _material_sort_dict:
  633. continue
  634. self.check_state_end()
  635. pp_jpg, pp_png = self.image_one_pic(
  636. goods_art_no, view_name, bg_color=None, return_orign=True
  637. )
  638. if not pp_jpg:
  639. continue
  640. file_name_index += 1
  641. # 获取对应主图模板
  642. if len(main_pic_path_list) < file_name_index + 1:
  643. main_pic_path = main_pic_path_list[-1]
  644. else:
  645. main_pic_path = main_pic_path_list[file_name_index]
  646. pp_bg = PictureProcessing(main_pic_path)
  647. original_width = pp_bg.width
  648. if original_width != 1600:
  649. pp_bg = pp_bg.resize(value=1600)
  650. if mask_pic:
  651. mask_bg = PictureProcessing(mask_pic)
  652. mask_bg = mask_bg.resize(value=1600)
  653. mask_box_im = mask_bg.get_im()
  654. box_size = mask_box_im.getbbox()
  655. result_image = mask_box_im.crop(box_size)
  656. mask_width, mask_height = result_image.size
  657. mask_x, mask_y = box_size[0], box_size[1]
  658. else:
  659. mask_width, mask_height = pp_bg.size
  660. mask_width, mask_height = int(mask_width * 12 / 16), int(
  661. mask_height * 12 / 16
  662. )
  663. mask_x, mask_y = int((pp_bg.size[0] - mask_width) / 2), int(
  664. (pp_bg.size[1] - mask_height) / 2
  665. )
  666. if view_name != "后跟":
  667. pp_jpg = pp_jpg.resize(base_by_box=(mask_width, mask_height))
  668. pp_png = pp_png.resize(base_by_box=(mask_width, mask_height))
  669. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  670. p_x = mask_x + int((mask_width - pp_jpg.width) / 2)
  671. p_y = mask_y + int((mask_height - pp_jpg.height) / 2)
  672. pp_bg = pp_bg.to_overlay_pic_advance(
  673. mode="pixel",
  674. top_img=pp_jpg,
  675. base="nw",
  676. value=(p_x, p_y),
  677. top_png_img=pp_png,
  678. )
  679. else:
  680. new_mask_width, new_mask_height = int(mask_width / 1.6), int(
  681. mask_height / 1.6
  682. )
  683. pp_jpg = pp_jpg.resize(
  684. base_by_box=(new_mask_width, new_mask_height)
  685. )
  686. pp_png = pp_png.resize(
  687. base_by_box=(new_mask_width, new_mask_height)
  688. )
  689. new_mask_x = int((mask_width - new_mask_width) / 2 + mask_x)
  690. new_mask_y = int((mask_height - new_mask_height) / 2 + mask_y)
  691. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  692. p_x = new_mask_x + int((new_mask_width - pp_jpg.width) / 2)
  693. p_y = new_mask_y + int((new_mask_height - pp_jpg.height) / 2)
  694. pp_bg = pp_bg.to_overlay_pic_advance(
  695. mode="pixel",
  696. top_img=pp_jpg,
  697. base="nw",
  698. value=(p_x, p_y),
  699. top_png_img=pp_png,
  700. )
  701. out_pci_mode = "." + settings.getSysConfigs(
  702. "basic_configs", "image_out_format", "png"
  703. )
  704. goods_no_main_pic_number += 1
  705. out_pic_path = "{out_path_root}/{goods_no}({goods_no_main_pic_number}){pic_mode}".format(
  706. out_path_root=out_path_root,
  707. goods_no=self.goods_no,
  708. goods_no_main_pic_number=goods_no_main_pic_number,
  709. pic_mode=out_pci_mode,
  710. )
  711. out_pci_factor = float(
  712. 1
  713. if settings.getSysConfigs(
  714. "basic_configs", "image_sharpening", "1"
  715. )
  716. == ""
  717. else settings.getSysConfigs(
  718. "basic_configs", "image_sharpening", "1"
  719. )
  720. )
  721. if out_pci_factor > 1.0:
  722. print("图片锐化处理")
  723. pp_bg = pp_bg.sharpen_image(factor=out_pci_factor)
  724. if original_width < 1600:
  725. pp_bg = pp_bg.resize(value=original_width)
  726. print("392 out_pic_path", out_pic_path)
  727. if out_pci_mode == ".jpg":
  728. pp_bg.save_as_rgb(out_pic_path)
  729. elif out_pci_mode == ".png":
  730. pp_bg.save_as_png(out_pic_path)
  731. else:
  732. pp_bg.save_as_other(out_pic_path, out_pci_mode.split(".")[-1])
  733. def add_pic(self, detailed_images):
  734. self.check_state_end()
  735. todo_detailed_images = []
  736. detailed_images = [x for x in detailed_images if x]
  737. if not detailed_images:
  738. return
  739. for i in detailed_images:
  740. if isinstance(i, list):
  741. for n in i:
  742. todo_detailed_images.append(n)
  743. else:
  744. todo_detailed_images.append(i)
  745. page_len = 0
  746. for index, pp in enumerate(todo_detailed_images):
  747. page_len += pp.height
  748. bg_im = Image.new("RGB", (pp.width, page_len), (255, 255, 255))
  749. n = 0
  750. for index, pp in enumerate(todo_detailed_images):
  751. bg_im.paste(pp.im, (0, n))
  752. n += pp.height
  753. return bg_im
  754. # 通用方法,用于写文字
  755. def add_text_list(self, text_list, spacing=5, base="wn", base_width=1600):
  756. text_list = [x for x in text_list if x["text"]]
  757. # print(text_list)
  758. # spacing 行间距
  759. text_image_list = []
  760. max_w = 0
  761. total_h = 0
  762. for text_data in text_list:
  763. _pp = PictureProcessing("RGBA", (base_width, 1200), (255, 255, 255, 0))
  764. if base == "wn" or base == "nw":
  765. align = "left"
  766. anchor = None
  767. value = (0, 250)
  768. if base == "cn" or base == "nc":
  769. align = "center"
  770. anchor = "mm"
  771. value = (int(base_width / 2), 250)
  772. if base == "en" or base == "ne":
  773. align = "right"
  774. anchor = "rs"
  775. value = (base_width - 10, 250)
  776. _pp = _pp.get_text_image_advanced(
  777. value=value,
  778. font=text_data["font"],
  779. text=text_data["text"],
  780. align=align,
  781. anchor=anchor,
  782. spacing=5,
  783. fill=text_data["fill"],
  784. return_mode="min_image",
  785. margins=(0, 0, 0, 0),
  786. )
  787. text_image_list.append(_pp)
  788. if _pp.width > max_w:
  789. max_w = _pp.width
  790. total_h += _pp.height
  791. if "spacing" in text_data:
  792. total_h += text_data["spacing"]
  793. if not text_image_list:
  794. return None
  795. #
  796. bg = PictureProcessing("RGBA", (max_w, total_h * 3), (0, 0, 0, 0))
  797. y = 0
  798. for text_image, text_data in zip(text_image_list, text_list):
  799. bg = bg.paste_img(top_img=text_image, value=(0, y), base=base)
  800. y += spacing + text_image.height
  801. if "spacing" in text_data:
  802. y += text_data["spacing"]
  803. bg = bg.crop(mode="min")
  804. # _ = bg.paste_img_invert(top_img=PictureProcessing("RGB", (bg.width,bg.height), (255, 255, 255)))
  805. # _.show()
  806. return bg
  807. def generate_font_list_to_pic(self):
  808. font_path_list = [
  809. r"resources\ttf\puhui\Bold.ttf",
  810. r"resources\ttf\puhui\Medium.ttf",
  811. r"resources\ttf\puhui\Heavy.ttf",
  812. r"resources\ttf\puhui\Light.ttf",
  813. r"resources\ttf\puhui\Regular.ttf",
  814. ]
  815. text_v_list = [
  816. "这是一段话Bold",
  817. "这是一段话Medium",
  818. "这是一段话Heavy",
  819. "这是一段话Light",
  820. "这是一段话Regular",
  821. ]
  822. detailed_images = []
  823. for font_path, text in zip(font_path_list, text_v_list):
  824. text_list = []
  825. for size in range(26, 80, 2):
  826. font = ImageFont.truetype(font_path, size)
  827. text_list.append(
  828. {
  829. "text": "{}-字号{}".format(text, size),
  830. "font": font,
  831. "fill": (110, 110, 110),
  832. }
  833. )
  834. text_image = self.add_text_list(text_list, spacing=15, base="nw")
  835. text_image = text_image.crop(mode="min")
  836. text_image = text_image.paste_img_invert(
  837. top_img=PictureProcessing("RGB", text_image.size, (255, 255, 255))
  838. )
  839. detailed_images.append(text_image)
  840. return PictureProcessing(im=self.add_pic(detailed_images))
  841. # 图片分段,每段至少大于N长度
  842. def pp_pic_subsection(self, pp: PictureProcessing, one_height=3200):
  843. total_height = pp.height
  844. now_height = 0
  845. detailed_images = []
  846. while 1:
  847. if now_height + one_height < total_height:
  848. h1 = now_height
  849. h2 = now_height + one_height
  850. bbox = (0, h1, pp.width, h2)
  851. # print("bbox1", bbox)
  852. detailed_images.append(pp.crop(bbox=bbox))
  853. now_height = now_height + one_height
  854. continue
  855. if now_height + one_height >= total_height:
  856. h1 = now_height
  857. h2 = total_height
  858. bbox = (0, h1, pp.width, h2)
  859. # print("bbox2", bbox)
  860. detailed_images.append(pp.crop(bbox=bbox))
  861. break
  862. return detailed_images