Well, there's no guarantee that you won't find FFD9 within a jpeg image. The best way you can find the end of a jpeg image is to parse it. Every marker, except for FFD0 to FFD9 and FF01(reserved), is immediately followed by a length specifier that will give you the length of that marker segment, including the length specifier but not the marker. FF00 is not a marker, but for your purposes you can treat it as marker without a length specifier.
The length specifier is two bytes long and it's big endian. So what you'll do is search for FF, and if the following byte is not one of 0x00, 0x01 or 0xD0-0xD8, you read the length specifier and skips forward in the stream as long as the length specifier says minus two bytes.
Also, every marker can be padded in the beginning with any number of FF's.
When you get to FFD9 you're at the end of the stream.
Of course you could read the stream word by word, searching for FF if you want performance but that's left as an exercise for the reader. ;-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…