如何以最有效的方式将图像转换为字符串?

发布于 2024-11-30 09:39:00 字数 310 浏览 0 评论 0原文

我想将图像文件转换为字符串。以下方法有效:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぶ宁プ宁ぶ 2024-12-07 09:39:00

在三点上,您会不必要地执行大型操作:

  1. 获取流的字节
  2. 将其转换为 Base64
  3. 将其写入 XmlWriter。

反而。首先调用LengthGetBuffer。这使您可以直接对流的缓冲区进行操作。 (不过,请先冲洗它)。

然后,自己实现base-64。它相对简单,因为您采用 3 个字节的组,进行一些位调整以获取要转换为的字符的索引,然后输出该字符。最后根据最后一个块发送的字节数添加一些 = 符号(= 表示一个剩余字节,==对于两个剩余字节,如果没有部分块则没有)。

将其写入字符缓冲区(char[])。最有效的大小需要实验,但我会从 2048 个字符开始。填充缓冲区后,对其调用 XmlWriter.WriteRaw,然后再次从索引 0 处开始写回。

这样,您就可以减少分配,并且从将图像加载到内存流中时就开始输出。一般来说,这应该会带来更好的吞吐量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文