In Linux/Unix systems, the file type is determined not based on the file name, that is, the file type is not determined based on the file suffix. I have downloaded an image from the Internet without a suffix and want to correctly determine the format so that it can be shared with other platforms. What should I do?
Different file types have different header information. popular image formats include JPG, PNG, and GIF. The following lists JPG, PNG, and GIF file headers (in hexadecimal format ):
JPEG (JPG), file header: ffd8ff
PNG (PNG), file header: 89504e47
GIF, file header: 47494638
With the file header, it is easy to judge the file. Read the header information of the image file and then compare it. Many existing editors can directly read the binary information of a file. The following uses xxd to read and Judge binary information:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#! /Bin/bash # Judge image file type
# Determining whether there is only one parameter If [$ #! = 1] Then Echo "parameter error" Else # Read The hexadecimal format corresponding to the first three bytes and the first four bytes Len3 = 'xxd-p-L 3 $1' Len4 = 'xxd-P-l 4 $1' If [$ len3 = "ffd8ff"] Then Echo "the type is jpg" Elif [$ len4 = "89504e47"] Then Echo "the type is PNG" El'if [$ len4 = "47494638"] Then Echo "the type is GIF" Else Echo "the type is others" Fi Fi |
For more articles, go to xiaopengxuan.
Determine the image format