如何将Image转换为字符串最有效的方法? [英] how to convert Image to string the most efficient way?

查看:119
本文介绍了如何将Image转换为字符串最有效的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图片文件转换为字符串。以下工作:

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:


  1. 获取流的字节

  2. 将其转换为Base64

  3. 将其写入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转换为字符串最有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆