目录
1. 获取gif图片第一帧,添加文字,获取图片的base64和md5
python在内存中处理图片
python 2.7
1. 获取gif图片第一帧,添加文字,获取图片的base64和md5
import requests
import io
from PIL import ImageFont, ImageDraw, Image, ImageSequence
import numpy as np
import cv2
import base64
import hashlib
req = requests.Session()
response = req.get(picUrl)
if response.status_code == 200:
image_data = response.content
image = io.BytesIO(image_data)
gif = Image.open(image)
# gif图片, 这里只处理一帧
for i, frame in enumerate(ImageSequence.Iterator(gif), 1):
# bytesio
out = io.BytesIO()
frame.save(out, format="PNG")
out.seek(0)
file_bytes = np.asarray(bytearray(out.read()), dtype=np.uint8)
bk_img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
# 设置需要显示的字体
font = ImageFont.truetype("./STSONG.TTF", 13)
img_pil = Image.fromarray(bk_img)
draw = ImageDraw.Draw(img_pil)
# 图片的指定位置处,添加2组文字
addText_1 = "hello"
addText_2 = "world"
draw.text((90, 30), addText_1.decode('utf-8'), font = font, fill = (0, 0, 0))
draw.text((90, 45), addText_2.decode('utf-8'), font = font, fill = (0, 0, 0))
del draw
bk_img = np.array(img_pil)
image_data = cv2.imencode('.png',bk_img)[1].tostring()
# base64, md5
image_base64 = base64.b64encode(image_data)
image_md5 = hashlib.md5(image_data).hexdigest()
break
2. pyplot绘图后,获取图片的base64和md5
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from io import BytesIO
from base64 import b64encode
from hashlib import md5
plt.figure()
plt.plot(x_date, y_data, color='red', label='test_data')
# plt.show()
figData = BytesIO()
plt.savefig(figData, format='png')
figData.seek(0) # rewind to begining of the figData
image_data = figData.read()
# image_data = figData.getvalue()
image_base64 = b64encode(image_data)
image_md5 = md5(image_data).hexdigest()
附1. python2.7 pip安装
wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
python get-pip.py