fix logic when encoding image