Your code will not work because the image data might contain the JPEG markers too (here: the FF D9 end of image marker).
So you have to write a parser that gets also the segment length for all non stand alone markers. When such a segment is processed, pass all bytes of the length without checking for markers. You might have to handle also compressed data which have no length but stop at the next 0xff marker not followed by 0x00 (0x00 is inserted in compressed data after all 0xff bytes).
I suggest to read about the JPEG file format.
JPEG File Interchange Format - Wikipedia[
^] might be a starting point.
Pseudo code (without pending checks):
if (seg_length)
{
int len = PassSegment(pstart, seg_length);
pstart += len;
seg_length -= len;
}
else if (compressed)
{
int len = PassCompressed(pstart);
pstart += len;
if (pstart[0] == 0xff && pstart[1])
compressed = 0; }
else if (pstart[0] == 0xff)
{
if (MarkerHasLength(pstart[1]))
{
seg_length = pstart[2] * 256 + pstart[3] - 2;
pstart += 2; }
else if (pstart[1] == 0xda)
{
compressed = 1;
}
pstart += 2; }
else
{
}