refactor generate_image method