How can you identify an image format without a filename extension?

Image.open identifies supported formats from their contents and accepts a binary file object.

Pixel experiment and interpretation

Save a PNG to an unnamed memory stream and reopen it. Its format is still identified. Recognition occurs before all pixel data has necessarily been decoded.

from PIL import Image
from io import BytesIO

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

buf=BytesIO()
row([9]).save(buf,format='PNG')
buf.seek(0)
with Image.open(buf) as im:
    fmt=im.format
fmt

Result 'PNG'

中文

没有文件扩展名时怎样识别图像格式?

Image.open 从文件内容识别格式,能直接接受二进制文件对象。

像素实验与适用边界

把一个 PNG 存进没有名字的内存流再打开,format 仍能报告 PNG。识别格式与读完全部像素是不同阶段。

from PIL import Image
from io import BytesIO

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

buf=BytesIO()
row([9]).save(buf,format='PNG')
buf.seek(0)
with Image.open(buf) as im:
    fmt=im.format
fmt

结果 'PNG'

References / 参考来源

Keep reading / 继续阅读