Have you gtaken a close look at wheat your saving into the .jpg file, there might be some extra data being sent before the image same way info is sent before a webpage contents, thus making it an invalid jpg file, try a hexeditor on the file, and see whats at the front of it, its liekly text, that you can see and thus isolate before starting the bwrites.