如何以最有效的方式将图像转换为字符串?
我想将图像文件转换为字符串。以下方法有效:
MemoryStream ms = new MemoryStream();
Image1.Save(ms, ImageFormat.Jpeg);
byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);
但是,将其保存到 XmlWriter 时,需要很长时间才能保存(26k 图像文件需要 20 秒)。有没有办法加快这个动作?
谢谢,
拉克斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在三点上,您会不必要地执行大型操作:
反而。首先调用
Length
和GetBuffer
。这使您可以直接对流的缓冲区进行操作。 (不过,请先冲洗它)。然后,自己实现base-64。它相对简单,因为您采用 3 个字节的组,进行一些位调整以获取要转换为的字符的索引,然后输出该字符。最后根据最后一个块发送的字节数添加一些
=
符号(=
表示一个剩余字节,==
对于两个剩余字节,如果没有部分块则没有)。将其写入字符缓冲区(char[])。最有效的大小需要实验,但我会从 2048 个字符开始。填充缓冲区后,对其调用
XmlWriter.WriteRaw
,然后再次从索引 0 处开始写回。这样,您就可以减少分配,并且从将图像加载到内存流中时就开始输出。一般来说,这应该会带来更好的吞吐量。
There are three points where you are doing large operations needlessly:
Instead. First call
Length
andGetBuffer
. 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.