如何使用其内容识别图像文件格式?

How to recognize an image file format using its contents?

如果图像文件的格式为 .png,那么它将在文件开头包含 ‰PNG . (在 Text 模式下阅读时)

如果图像文件的格式为 .bmp,那么它将在文件开头包含 BM。 (在 Text 模式下阅读时)

我知道图像格式在文件的开头包含一定大小(字节)的文本(数据),用作图像文件的元数据?

我的问题是:-

Is this behavior same in all image file formats (or formats in general)?

对他们中的大多数人来说,是的。有一些专有格式(例如游戏)可能有非常短的元数据或没有元数据。此外,元数据可能在另一个文件中(例如动画和 XML 元数据)。

Could a image file (of no extension) be recognized just using this data?

是的。事实上,如果图像文件的扩展名不正确,大多数图像查看器都会警告您,并询问您是否应该修复它。

在 Unix 系统上,file command that identifies files based on their metadata. There is a better tool specific for images called identify (part of ImageMagick) returns 有关分辨率、位深度等的更详细信息

Is there information available on how this metadata is broken down? By that I mean, data at which position in the metadata has what meaning?

有关于(图像)文件格式的书籍,对于大多数格式,此信息可在官方规范中找到(例如 RFC 2083 for PNG). They list all of the (optional) file contents, describe the compressions and what a viewer/decoder/encoder can/must/should do with the data. A good starting point might be the Wikipedia list of image file formats

请注意,根据您提供的示例,我假设您使用文本编辑器打开文件,这不是该任务的理想工具。最好用一个 hex-editor for this. Text editors won't show most bytes (e.g. 255) by default and interprete others (e.g. tab or line feed). They might be good enough to see magic text strings like "BM" and "PNG", but with a hex editor, you can see both these text parts and their numerical representation - e.g. allowing you to extract image width and height. For this, some tool to convert hexademical 值转十进制很有用,大多数计算器都可以做到这一点。

例如,让我们在文本编辑器和十六进制编辑器中查看分辨率为 6146 x 14293 的 PNG 文件的开头:

你可以看到这两个文件都是PNG图片,没错。但是十六进制编辑器视图中标记的部分会显示图像的宽度和高度(匹配PNG chunk specification of the "IHDR" part) - 0x00001802十进制为6146,0x000037D5为14293。没有办法在文本编辑器中执行此操作。

另请注意,即使您不知道图像格式,您也可能会幸运地猜测它是未压缩的数据(这通常适用于某些游戏图像文件格式,最著名的是 Unity 的“资产”)。例如。如果您将文件重命名为“.raw”,图像查看器 IrfanView 会给您一个对话框(见下面的屏幕截图),您可以在其中猜测图像的宽度、高度和位深度,并查看结果是否不错。不过,这需要一些解释结果的经验,如果宽度和位深度不匹配,图像将看起来像噪声、扭曲或颜色错误。

这种“图像几何猜测”可以通过尝试不同的宽度并计算两条线之间的相关系数来improved/automated。工具 raw2tiff 可以做到这一点。引自网站:

There is no magic, it is just a mathematical statistics, so it can be wrong in some cases. But for most ordinary images guessing method will work fine.

使用 Imagemagick,您可以获得 Imagemagick 可以从头文件中的 "magick" 数据中读取的格式信息(如果可用),如下所示:

convert image -format "%m\n" info:


例如:

convert lena.png -format "%m\n" info:
PNG

convert lena.jpg -format "%m\n" info:
JPEG

convert lena.pnm -format "%m\n" info:
PPM


即使去掉后缀,仍然有效:

convert lena_copy -format "%m\n" info:
PNG