Why specify a format when saving an image to memory?
save can infer the encoder from a filename. An unnamed byte stream needs an explicit format.
Pixel experiment and interpretation
Check the file signature after writing a PNG to memory. L describes pixels and cannot tell the encoder which container you want.
from PIL import Image
from io import BytesIO
def row(values):
return Image.frombytes('L', (len(values), 1), bytes(values))
buf=BytesIO()
row([7,8]).save(buf,format='PNG')
buf.getvalue()[:8].hex()Result '89504e470d0a1a0a'
中文
输出到内存时为何要显式指定编码格式?
save 可从文件名推断编码格式;没有可用扩展名的字节流需明确指定格式。
像素实验与适用边界
以 PNG 保存到内存后检查文件签名。模式 L 描述像素,无法告诉编码器你想选 PNG 还是其他容器。
from PIL import Image
from io import BytesIO
def row(values):
return Image.frombytes('L', (len(values), 1), bytes(values))
buf=BytesIO()
row([7,8]).save(buf,format='PNG')
buf.getvalue()[:8].hex()结果 '89504e470d0a1a0a'