Could you please provide more info about the problem you are trying to solve?
I don't see why you would need to change the product image on the fly at the front end...
Maybe there is a more streamlined and less hacky method than can achieve the result you want.