Fix empty images getting written

Fixes #163, #184 and #187.