问题描述
我想将图片文件转换为字符串。以下工作:
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);
但是,将此保存到XmlWriter时,它需要很长时间才能保存(26k图像需要20秒)文件)。有没有办法加快这个动作?
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?
谢谢,
Raks
推荐答案
有三点你不必要地进行大型操作:
There are three points where you are doing large operations needlessly:
- 获取流的字节
- 将其转换为Base64
- 将其写入XmlWriter。
相反。首先调用长度
和 GetBuffer
。这让你直接对流的缓冲区进行操作。 (尽管先冲洗它。)
Instead. First call Length
and GetBuffer
. This let's you operate upon the stream's buffer directly. (Do flush it first though).
然后,自己实现base-64。这是相对简单的,因为你采取3个字节的组,做一些bit-twiddling索引到它将被转换为的字符,然后输出该字符。在最后,根据最后一个块发送的字节数( =
),添加一些 =
符号余数字节, ==
表示两个剩余字节,如果没有部分块,则为无。)
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).
执行此操作进入char缓冲区(char [])。最有效的尺寸是实验的问题,但我从2048个字符开始。当您填充缓冲区时,在其上调用 XmlWriter.WriteRaw
,然后再次开始在索引0处回写。
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.
这篇关于如何将Image转换为字符串最有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!