I can't tell by looking at your code, what's wrong. My suggestion is you alter your code temporarily, and have it put out EXACTLY the same pic.
Now you can use utilities like "fc /b filename filename" (but check it with "fc /?", because I haven't used it in a long time), to do a binary comparison of the files and see where the differences are - and thus find your error. (Linux has similar tools).
Looking at an altered image, it's very hard to see the exact pixels that are wrong. Looking at two versions of the SAME image, when magnified with something like Windows Paint, or any image editing program, it because a LOT easier.