pic_deal.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. from PIL import Image
  2. from io import BytesIO
  3. from service.remove_bg_ali import RemoveBgALi as RemoveBg
  4. class Picture:
  5. def __init__(self, in_path):
  6. self.im = Image.open(in_path)
  7. self.x, self.y = self.im.size
  8. # print(self.x, self.y)
  9. def resize_regular(self, width, high):
  10. self.im = self.im.resize((width, high), Image.Resampling.LANCZOS)
  11. def save_img(self, out_path, quality=90):
  12. # self.im = self.im.convert("RGB")
  13. self.im.save(out_path, quality=quality)
  14. def crop_with_png(self):
  15. self.im = self.im.crop(self.im.getbbox())
  16. self.x, self.y = self.im.size
  17. def resize(self, width=None, high=None):
  18. if width:
  19. re_x = int(width)
  20. re_y = int(self.y * re_x / self.x)
  21. else:
  22. re_y = int(high)
  23. re_x = int(self.x * re_y / self.y)
  24. self.im = self.im.resize((re_x, re_y))
  25. self.x, self.y = self.im.size
  26. def save_to_io(self, format):
  27. img = BytesIO()
  28. self.im.save(img, format=format) # format: PNG or JPEG
  29. img.seek(0) # rewind to the start
  30. return img
  31. def corp_square(self):
  32. if self.y < self.x:
  33. return
  34. self.im = self.im.crop((0, int((self.y - self.x) / 2), self.x, self.y - int((self.y - self.x) / 2)))
  35. class PicDeal(object):
  36. def __init__(self):
  37. self.mode = "ali"
  38. def remove_bg(self, in_path, out_path):
  39. """
  40. 1、三方软件进行抠图处理
  41. 2、图片进行清晰度转化,转化成原始图片尺寸
  42. """
  43. if Remove_Bg_Mode == "zuo_tang" or Remove_Bg_Mode == "ali":
  44. remove_bg_ins = RemoveBg()
  45. if remove_bg_ins.run(in_path, out_path):
  46. return True
  47. else:
  48. return False
  49. def create_800image(self, original_image, cut_image_path, out_path, image_mode=None):
  50. """
  51. image_mode: 处理模式,主要用于图片缩放大小确定
  52. original_image:原始图,用于获取商品阴影
  53. cut_image_path:抠图结果
  54. """
  55. image = Picture(original_image)
  56. image.crop_with_png()
  57. # image.im.show()
  58. if image.x >= image.y:
  59. image.resize(width=575)
  60. else:
  61. image.resize(high=575)
  62. image_bg = Image.open("resources/goods_bg.jpg")
  63. image_bg_x, image_bg_y = image_bg.size
  64. image_x, image_y = image.x, image.y
  65. _x = int((image_bg_x - image_x) / 2)
  66. _y = int((image_bg_y - image_y) / 2)
  67. image_bg.paste(image.im, (_x, _y), image.im)
  68. # image_bg.show()
  69. image_bg.save(out_path)
  70. def resize_and_save(self, image_path, out_path, width):
  71. im = Image.open(image_path)
  72. x, y = im.size
  73. re_x = int(width)
  74. re_y = int(y * re_x / x)
  75. im = im.resize((re_x, re_y), Image.ANTIALIAS)
  76. im.save(out_path)
  77. def save(self, out_path):
  78. pass
  79. if __name__ == '__main__':
  80. pass