refactored the image downloading function