I've worked on an image to project on a surface. I requested to write name to given surface.
It was very straight forward to combine a image from letter jpgs to write name.
Then second part of problem becomes same with your question: project image on a surface. But I knew the dimensions. In video you need to also match the color (greenbox) you want to replace with picture. After you gather 4 points (topleft, topright, bottomright, bottomleft). You need to solve matrix transformation. Every pixel in the destination should be derived the photo you have.
http://en.wikipedia.org/wiki/Matrix_transformations
By using C, it could be reasonably fast. But php can't.