功能:
1、图片URL,下载图片
2、图片URL,返回图片格式尺寸img.format, img.size
3、本地图片,返回图片格式尺寸等信息
4、图片转二进制
5、二进制转为图片
6、图片转base64
7、base64转为图片
8、获取图片MD5值
# !/usr/bin/env python
# -*-coding:utf-8 -*-
import base64,os
import requests
from urllib import request
from PIL import Image
import imghdr
import hashlib
def download_image(picurl,picpath):
'''URl下载图片'''
r = requests.request('get', picurl) # 图片url
if r.status_code == 200:
with open(picpath, 'wb') as f: # 打开写入到path路径里-二进制文件,返回的句柄名为f
f.write(r.content)
else:
print(f"{picurl},下载图片失败")
def url_picinfo(picurl):
'''图片URL,返回图片格式尺寸img.format, img.size'''
res = request.urlopen(picurl)
img = Image.open(res)
imginfo = {'format':img.format,'size':img.size}
return imginfo
# image = requests.get(picurl).content
# image_b = io.BytesIO(image).read()
# return imghdr.what(None, h=image_b)
def path_picinfo(picpath):
'''本地图片,返回图片格式尺寸等信息'''
imgByte = os.path.getsize(picpath) # 检测文件大小函数
img = Image.open(picpath)
imginfo = {'size':img.size,'height':img.height,'width':img.width,'mode':img.mode,'format':img.format}
img.close()
return imginfo
def image_to_byte(imagepath):
'''
图片转二进制
'''
with open(imagepath,"rb") as f:
byte_data = f.read()
return byte_data
def byte_to_image(byte_data,imagepath):
'''
二进制转为图片
imagepath:图片保存路径
'''
with open(imagepath, "wb") as f:
f.write(byte_data)
def image_to_base64(imagepath):
'''
图片转base64
'''
with open(imagepath,"rb") as f:
base64_data = base64.b64encode(f.read()).decode("utf8") # 读取文件内容,转换为base64编码
return base64_data
def base64_to_image(base64_data,imagepath):
'''
base64转为图片
imagepath:图片保存路径
'''
with open(imagepath, "wb") as f:
f.write(base64.b64decode(base64_data))
def get_image_md5(picpath):
"""获取图片MD5值"""
with open(picpath, 'rb') as f: # 打开写入到path路径里-二进制文件,返回的句柄名为f
return hashlib.md5(f.read()).hexdigest()
if __name__ == "__main__":
# res = image_to_byte(r'E:\Attachments\NN7469.png')
# print(res)
# res = image_to_base64(r'E:\Attachments\NN7469.png')
# print(res)
# picpath = r'E:\Attachments\MM7469.png'
# base64_to_image(res,picpath)
print(path_picinfo(r'E:\Attachments\M_615.png'))