Skip to content

Instantly share code, notes, and snippets.

@toashd
Created March 30, 2016 13:00
Show Gist options
  • Save toashd/65aec10bc9c66466b49b89a8ff7f86fb to your computer and use it in GitHub Desktop.
Save toashd/65aec10bc9c66466b49b89a8ff7f86fb to your computer and use it in GitHub Desktop.
Determine image file format in golang.
// 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