replaced image painting code (according to StackOverflow, this variant
is faster)