Skip to content

Instantly share code, notes, and snippets.

@slav123
Created December 13, 2017 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slav123/0b1c3a6212653a8617695a4d9973612c to your computer and use it in GitHub Desktop.
Save slav123/0b1c3a6212653a8617695a4d9973612c to your computer and use it in GitHub Desktop.
Gets the JPEG size from the array of data passed to the function
func jpegDimensions(data []byte) (int32, int32) {
var width, height, i int
data_size := cap(data)
if data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0 {
i += 4
if data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && data[i+5] == 'F' && data[i+6] == 0x00 {
block_length := int(data[i])*256 + int(data[i+1])
for i < data_size {
i += block_length //Increase the file index to get to the next block
if i >= data_size {
return -1, -1 //Check to protect against segmentation faults
}
if data[i] != 0xFF {
return -1, -1 //Check that we are truly at the start of another block
}
if data[i+1] == 0xC0 {
//0xFFC0 is the "Start of frame" marker which contains the file size
//The structure of the 0xFFC0 block is quite simple [0xFFC0][ushort length][uchar precision][ushort x][ushort y]
height = int(data[i+5])*256 + int(data[i+6])
width = int(data[i+7])*256 + int(data[i+8])
return int32(width), int32(height)
} else {
i += 2 //Skip the block marker
block_length = int(data[i])*256 + int(data[i+1]) //Go to the next block
}
}
}
}
return 0, 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment