for anyone who wants to read comments. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Gets the JPEG size from the array of data passed to the function, file reference: http://www.obrador.com/essentialjpeg/headerinfo.htm
static char get_jpeg_size(unsigned char* data, unsigned int data_size) {
//Check for valid JPEG image
int i=0; // Keeps track of the position within the file
unsigned char comment[1024];
if(data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0) {
i += 4;
// Check for valid JPEG header (null terminated JFIF)
if(data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && data[i+5] == 'F' && data[i+6] == 0x00) {
//Retrieve the block length of the first block since the first block will not contain the size of file
unsigned short block_length = data[i] * 256 + data[i+1];
while(i<data_size) {
i+=block_length; //Increase the file index to get to the next block
printf("%x,%x\n", data[i], data[i+1]);
if(i >= data_size) return false; //Check to protect against segmentation faults
if(data[i] != 0xFF){ printf("Byte is not 0xFF, Exiting\n"); return false;} //Check that we are truly at the start of another block
if(data[i+1] == 0xFE) { //0xFFFE is the "Start of Comment" marker which contains comment
//The structure of the 0xFFFE block is quite simple [0xFFFE][Comment]
unsigned short comment_len = data[i+2]*256 + data[i+3] - 2;
strncpy((char*)comment, (char*)(data+(i+4)), comment_len);
printf("Comment is: %s\n", comment);
}
i+=2; //Skip the block marker
block_length = data[i] * 256 + data[i+1]; //Go to the next block
}
return false; //If this point is reached then no size was found
}else{ return false; } //Not a valid JFIF string
}else{ return false; } //Not a valid SOI header
}
int main(int argc, char* argv[])
{
FILE* pFile;
long size;
unsigned char* buffer;
unsigned short width, height;
size_t result;
pFile = fopen(argv[1], "rb");
if (pFile == NULL) {perror ("Error opening file"); exit(1);}
fseek(pFile, 0, SEEK_END);
size = ftell(pFile);
rewind(pFile);
buffer = (unsigned char*)malloc(sizeof(char)*size);
if (buffer == NULL) {fputs ("Memory Error",stderr); exit(2);}
result = fread(buffer, 1, size, pFile);
if (result != size) {printf("size=%d, result=%d\n", size, result);perror("Reading File"); exit(3);}
get_jpeg_size(buffer, size);
fclose(pFile);
free (buffer);
return 0;
}
Bookmarks