add image dimension check, rearrange some code