Fixed potential memory leak in writeImage