Checking JPEG image dimension from partial headers

Page content

The goal was to read image dimensions from an image file. Pretty easy task with standard “ image ” library and DecodeConfig. The tricky part was – the file wasn’t completed – I had only the beginning of the file. I tried to decode headers by myself. I didn’t find an exact recipe in GO and found many people looking for correct answers in many languages.

PNG headers

Let’s start with the easy one. PNG headers are pretty standard – everything is in place. Just need to read beginning of the file to array, and decode it like that

var body []byte
    offset := 16
    width := int32(binary.BigEndian.Uint32(body[offset : offset+4]))
    height := int32(binary.BigEndian.Uint32(body[(offset + 4) : offset+12]))

JPEG headers

Here we have more problems. JPEG is very flexible, and you can put a lot of rubbish into the file itself. Thanks to that, it has a unique header structure, where it’s not so obvious where dimensions are encoded. You have to read the file, look for headers, decode them – find the correct one and then get the width & height.

I’ve been using not existing website as a reference: www.64lines.com/jpeg-width-height . I found this piece of code 

which surprisingly works. My GO code looks pretty much similar: