Programmatically add template to images

As per the title, is there a way to loop through all the images and add the correct template?