Check that images have valid dimensions (issue 4575)

Attempting to fix #4575.