CRM-14646 - optimze image display upgrade code

----------------------------------------
* CRM-14646: new image display upgrade code not optimized, can result in
error
 https://issues.civicrm.org/jira/browse/CRM-14646

(This is a cherry-pick/resubmission of https://github.com/civicrm/civicrm-core/pull/3173 )