$refreshCachedImages = 1to earlier in the problem. Currently, it is after the image is referenced the problem. I'm not sure when it has its effect, but I suspect the image is created and linked in at the point where the image is referenced, and that is probably where the value of
$refreshCachedImagesis used. Changing it afterword would have no effect in that case.