You're doing far too much work for most of this. See
how I did the task in my column. ImageToBlob means you don't have to fetch each pixel. A single sprintf to get the colors to hex. And your scaling can be drastically reduced... by default, if you say "resize to 50x50", you get a proportionate scaledown that makes the largest dimension 50 but the smaller dimension appropriate! No math required.
-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.