简体   繁体   English

如何将Image转换为字符串最有效的方法?

[英]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). 但是,将其保存到XmlWriter时,它需要很长时间才能保存(26k图像文件为20秒)。 Is there a way to speed this action up? 有没有办法加速这个动作?

Thanks, 谢谢,

Raks RAKS

There are three points where you are doing large operations needlessly: 有三点你不必要地进行大型操作:

  1. Getting the stream's bytes 获取流的字节
  2. Converting it to Base64 将其转换为Base64
  3. Writing it to the XmlWriter. 将它写入XmlWriter。

Instead. 代替。 First call Length and GetBuffer . 首先调用LengthGetBuffer This let's you operate upon the stream's buffer directly. 这让你直接对流的缓冲区进行操作。 (Do flush it first though). (尽管先冲洗它)。

Then, implement base-64 yourself. 然后,自己实现base-64。 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. 这是相对简单的,因为你采取3个字节的组,做一些bit-twiddling索引到它将被转换为的字符,然后输出该字符。 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[]). 将此写入char缓冲区(char [])。 The most efficient size is a matter for experimentation but I'd start with 2048 characters. 最有效的尺寸是实验的问题,但我从2048个字符开始。 When you've filled the buffer, call XmlWriter.WriteRaw on it, and then start writing back at index 0 again. 填充缓冲区后,在其上调用XmlWriter.WriteRaw ,然后再次开始在索引0处回写。

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. 通常,这应该导致更好的吞吐量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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