问题描述
base64 的 image/tiff 无法在页面直接展示,将其转换为 image/png
解决方案
from io import BytesIO
from PIL import Image
with Image.open('a.tiff') as image:
bytesIO = BytesIO()
image.save(bytesIO, format='PNG', quality=75)
img = bytesIO.getvalue()
with open('a.png', 'wb') as f: # 写入图片
f.write(img)
压缩并转换
from io import BytesIO
from PIL import Image
with Image.open('a.tiff') as image:
width, height = image.size
target_width = 500 # 目标宽度
if width > target_width:
height = round(target_width * height / width)
width = target_width
size = (width, height)
image = image.resize(size)
bytesIO = BytesIO()
image.save(bytesIO, format='PNG', quality=75)
img = bytesIO.getvalue()
with open('a.png', 'wb') as f: # 写入图片
f.write(img)
直接转换
from PIL import Image
Image.MAX_IMAGE_PIXELS = None # 防止报错PIL.Image.DecompressionBombError
def tif_to_png(input_path, output_path, width=1000):
"""
:param input_path: tif文件路径
:param output_path: 导出文件路径
:param width: 目标宽度
:return:
"""
with Image.open(input_path) as image:
_width, _height = image.size # 原图宽高
height = int(width * _height / _width) # 目标高度,等比缩放
resize = image.resize((width, height)) # tif一般很大,等比缩放到合理大小
resize.save(output_path, quality=75)