# Python2.7.11
class Picture(object):
def __init__(self, file_path=None, temporary=False, base64_string=None):
self.base64_string = base64_string # base64的原图,博
self.comp_img = None # 压缩后的图片
self.comp_base64_string = None # 压缩后图片的base64
self.img_type = self.get_img_type() # 获取图片类型
self.pic_head = "data:image/%s;base64," % self.img_type # 组装图片头
self.img = self.open_img() # 根据图片形式转化为Image对象
def get_img_type(self):
self.img_type = re.search('^data:image/(.+);base64,', self.base64_string).group(1)
def open_img(self):
if self.file_path:
return Image.open(self.file_path)
else:
return self.convert_to_Image(self.base64_string)
def show(self):
return self.img
def convert_to_base64(self, img=None, format="png"):
if not img:
img = self.img
output_buffer = StringIO()
img.save(output_buffer, format=format.upper())
binary_data = output_buffer.getvalue()
base64_data = base64.b64encode(binary_data)
return base64_data
def convert_to_Image(self, base64_string):
base64_data = re.sub('^data:image/.+;base64,', '', base64_string)
binary_data = base64.b64decode(base64_data)
img_data = StringIO(binary_data)
return Image.open(img_data)
def compress_img(self, img=None, color=49, choice=False):
img = img if img else self.img
reimg = img.quantize(colors=color)
compress_ = self.pic_head + self.convert_to_base64(reimg)
# 保留压缩后的图片与原图中最小的那个
if choice:
self.comp_base64_string = compress_ if len(compress_) < len(self.base64_string) else self.base64_string
self.comp_img = img
return img
self.comp_img = reimg
self.comp_base64_string = compress_
return reimg
def calc_hashes(self, hash_type='origin'):
"""Calculate all possible hashes for this file."""
crc = 0
md5 = hashlib.md5()
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
sha512 = hashlib.sha512()
if hash_type == 'origin':
base64_string = self.convert_to_base64()
else:
base64_string = self.convert_to_base64(self.comp_img)
crc = binascii.crc32(base64_string, crc)
md5.update(base64_string)
sha1.update(base64_string)
sha256.update(base64_string)
sha512.update(base64_string)
self._crc32 = "".join("%02X" % ((crc >> i) & 0xff)
for i in [24, 16, 8, 0])
self._md5 = md5.hexdigest()
self._sha1 = sha1.hexdigest()
self._sha256 = sha256.hexdigest()
self._sha512 = sha512.hexdigest()
return self
07-12
1295
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交