JPEG extraction script
There is an End-of-data marker FF D9, but you can't scan for it blindly, because those bytes can also appear within a JPEG image. For example, if the JPEG contains a thumbnail, then FF D9 could mark the end of the thumbnail rather than of the whole image.  In fact, the FF D8 start-of-image marker can also appear within a JPEG image for the same reason.  Therefore, your technique is invalid.

To do a proper job, you must look for JPEG markers, most of which are followed by two bytes indicating the payload size, and advance the indicated number of bytes, until you hit the FF D9 marker.  It might even be faster, since you can advance in chunks rather than scanning every byte sequentially.