Fix potential memory leak when generating thumbnails.