detail_generate_base.py 34 KB

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