Moved image encoding into a closure passed to ImageData constructor.