Skip to content

Instantly share code, notes, and snippets.

@henkman
Last active January 20, 2023 00:33
Show Gist options
  • Save henkman/ce3a2cd85ee0d17bbd5adec46d47d269 to your computer and use it in GitHub Desktop.
Save henkman/ce3a2cd85ee0d17bbd5adec46d47d269 to your computer and use it in GitHub Desktop.
png, jpeg and gif: get image width and height
package main
import (
"bytes"
"encoding/binary"
"fmt"
"os"
)
func main() {
fd, err := os.Open(`your.gif`)
if err != nil {
panic(err)
}
defer fd.Close()
var buf [6]byte
fd.Read(buf[:6])
if !bytes.Equal([]byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61}, buf[:6]) {
panic("not a gif")
}
fd.Read(buf[:4])
width := binary.LittleEndian.Uint16(buf[0:2])
height := binary.LittleEndian.Uint16(buf[2:4])
fmt.Println(width, height)
}
package main
import (
"bytes"
"fmt"
"os"
)
func main() {
const F = `your.jpg`
data, err := os.ReadFile(F)
if err != nil {
panic(err)
}
o := 0
if !bytes.Equal([]byte{0xFF, 0xD8}, data[o:o+2]) {
panic("not a jpeg")
}
o += 2
var width, height int
for o < len(data) {
if data[o] != 0xFF {
panic("bad file")
}
if data[o+1] == 0xC2 || data[o+1] == 0xC0 {
height = int(data[o+5])*256 + int(data[o+6])
width = int(data[o+7])*256 + int(data[o+8])
break
} else {
o += 2
block_len := int(data[o])*256 + int(data[o+1])
o += int(block_len)
}
}
fmt.Println(width, height)
}
package main
import (
"bytes"
"encoding/binary"
"fmt"
"os"
)
func main() {
const F = `your.png`
fd, err := os.Open(F)
if err != nil {
panic(err)
}
defer fd.Close()
var buf [8]byte
fd.Read(buf[:])
if !bytes.Equal([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, buf[:]) {
panic("not a png")
}
fd.Read(buf[:])
if !bytes.Equal([]byte("IHDR"), buf[4:]) {
panic("bad png")
}
fd.Read(buf[:])
width := binary.BigEndian.Uint32(buf[0:4])
height := binary.BigEndian.Uint32(buf[4:8])
fmt.Println(width, height)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment