Finish the function to output the image and fix some bugs.