updated image saving algorithm