Checking JPEG image dimension from partial headers
The goal was to read image dimension from image file. Pretty easy task with standard “image” library and DecodeConfig. The tricky part was – file wasn’t completed – I had only beginning of the file . Obviously I tried to decode headers by myself. I didn’t found exact recipe in GO, and found a lot of people looking for correct answer in many languages.
Let’s start with the easy one. PNG headers are pretty standard – everything is in place. Just need to read begining 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]))
Here we have more problems. JPEG is very flexible, and you can put a lot of rubbish into file itself. Thanks to that it has special header structure, where it’s not so obvious where dimensions are encoded. You have to read file, look for headers, decode them – find correct one and then get width & height.
I’ve been using not existing website as a reference:http://www.64lines.com/jpeg-width-height. I found this piece of codewhich surprisingly works. My GO code looks pretty much similar: