I suggest going for format like TGA or BMP, they have much easier header build up to save an image as bytes.