Created
March 30, 2016 13:00
-
-
Save toashd/65aec10bc9c66466b49b89a8ff7f86fb to your computer and use it in GitHub Desktop.
Determine image file format in golang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// imageFormat returns the image format. | |
func imageFormat(file *os.File) string { | |
bytes := make([]byte, 4) | |
n, _ := file.ReadAt(bytes, 0) | |
file.Seek(0, 0) | |
if n < 4 { | |
return "" | |
} | |
if bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47 { | |
return "png" | |
} | |
if bytes[0] == 0xFF && bytes[1] == 0xD8 { | |
return "jpg" | |
} | |
if bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x38 { | |
return "gif" | |
} | |
if bytes[0] == 0x42 && bytes[1] == 0x4D { | |
return "bmp" | |
} | |
return "" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment