Be sure and use mode = P instead of RGB, like you have in your other code. P is for palettized images. Don't palettize if you're storing as JPG, only if you're storing as PNG or some other format that can handle 256 color images.