how to convert Image to string the most efficient way?

元气小坏坏 提交于 2019-12-07 14:14:41

问题


I want to convert an image file to a string. The following works:

MemoryStream ms = new MemoryStream();

Image1.Save(ms, ImageFormat.Jpeg);

byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);

However, when saving this to a XmlWriter, it takes ages before it's saved(20secs for a 26k image file). Is there a way to speed this action up?

Thanks,

Raks


回答1:


There are three points where you are doing large operations needlessly:

  1. Getting the stream's bytes
  2. Converting it to Base64
  3. Writing it to the XmlWriter.

Instead. First call Length and GetBuffer. This let's you operate upon the stream's buffer directly. (Do flush it first though).

Then, implement base-64 yourself. It's relatively simple as you take groups of 3 bytes, do some bit-twiddling to get the index into the character it'll be converted to, and then output that character. At the very end you add some = symbols according to how many bytes where in the last block sent (= for one remainder byte, == for two remainder bytes and none if there were no partial blocks).

Do this writting into a char buffer (a char[]). The most efficient size is a matter for experimentation but I'd start with 2048 characters. When you've filled the buffer, call XmlWriter.WriteRaw on it, and then start writing back at index 0 again.

This way, you're doing less allocations, and you're started on the output from the moment you've got your image loaded into the memory stream. Generally, this should result in better throughput.



来源:https://stackoverflow.com/questions/7118840/how-to-convert-image-to-string-the-most-efficient-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!