简体   繁体   中英

how to convert Image to string the most efficient way?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM