imagecopyresampled() produces rounding errors.
A simple example is trying to resample a fully transparent 560x349 image down to 100x62.
The resulting image will have transparency 2/255, not 0 as it was in the original image.
This is caused by a conversion to int without rounding - alpha/spixels is often something like 126.999999999, that is floored down to int 126, and then 126 is transformed into opacity=2.
The fix would be to change
red /= spixels; green /= spixels; blue /= spixels; alpha /= spixels;
red = red/spixels+0.5; green = green/spixels+0.5; blue = blue/spixels+0.5; alpha = alpha/spixels+0.5;