将字符串转换为流

23

我从互联网上下载了一张图片并将其转换为字符串(不可更改)

Dim Request As System.Net.WebRequest = _
  System.Net.WebRequest.Create( _
  "http://www.google.com/images/nav_logo.png")

Dim WebResponse As System.Net.HttpWebResponse = _
  DirectCast(Request.GetResponse(), System.Net.HttpWebResponse)

Dim Stream As New System.IO.StreamReader( _
  WebResponse.GetResponseStream, System.Text.Encoding.UTF8)

Dim Text as String = Stream.ReadToEnd

如何将字符串转换回流?

这样我就可以使用该流来获取图像。

像这样:

Dim Image As New Drawing.Bitmap(WebResponse.GetResponseStream)

但是现在我只有文本字符串,因此我需要像这样的东西:

Dim Stream as Stream = ReadToStream(Text, System.Text.Encoding.UTF8)
Dim Image As New Drawing.Bitmap(Stream)

编辑:

这个引擎主要用于下载网页,但我也想用它来下载图片。字符串的格式是UTF8,就像示例代码中给出的那样...

我尝试使用MemoryStream(Encoding.UTF8.GetBytes(Text)),但当将流加载到图像时出现了以下错误:

GDI+发生一般性错误。

在转换中有什么被遗漏了吗?


我会根据你的编辑进行更新。 - Marc Gravell
4个回答

41
为什么要把二进制(图像)数据转换为字符串?这毫无意义,除非你使用 base-64?
无论如何,要还原你所做的操作,可以尝试使用 `new MemoryStream(Encoding.UTF8.GetBytes(text))`?
这将创建一个新的 Memory Stream,通过 UTF8 将字符串填充到其中。个人认为它可能不起作用——当将原始二进制视为 UTF8 数据处理时,你会遇到许多编码问题……我预计读取或写入(或两者都有)都会引发异常。
(编辑)
我应该添加提醒,要使用 base-64,只需获取数据作为 `byte[]`,然后调用 `Convert.ToBase64String(...)`;要获取数组回来,只需使用 `Convert.FromBase64String(...)`。
关于您的编辑,这正是我上面试图提醒的……在 .NET 中,字符串不仅仅是一个 `byte[]`,因此你不能简单地用二进制图像数据填充它。许多数据对编码来说根本没有意义,因此可能被悄悄丢弃(或抛出异常)。
要将原始二进制文件(例如图片)作为字符串处理,需要使用 base-64 编码;但是这会增加大小。注意,WebClient 可能会使这更简单,因为它直接公开了 `byte[]` 功能:
using(WebClient wc = new WebClient()) {
    byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
    //...
}

无论如何,使用标准的Stream方法,以下是将base-64进行编码和解码的步骤:

        // ENCODE
        // where "s" is our original stream
        string base64;
        // first I need the data as a byte[]; I'll use
        // MemoryStream, as a convenience; if you already
        // have the byte[] you can skip this
        using (MemoryStream ms = new MemoryStream())
        {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, bytesRead);
            }
            base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
        }

        // DECODE
        byte[] raw = Convert.FromBase64String(base64);
        using (MemoryStream decoded = new MemoryStream(raw))
        {
            // "decoded" now primed with the binary
        }

4

这会起作用吗?我不知道你的字符串是什么格式,所以可能需要一些调整。

Dim strAsBytes() as Byte = new System.Text.UTF8Encoding().GetBytes(Text)
Dim ms as New System.IO.MemoryStream(strAsBytes)

1

按照您展示的方式将二进制数据转换为字符串会使其无用。您无法将其还原回去。文本编码会损坏它。

您需要使用Base64 - 就像@Marc所展示的那样。


1
var bytes = new byte[contents.Length * sizeof( char )];
Buffer.BlockCopy( contents.ToCharArray(), 0, bytes, 0, bytes.Length );
using( var stream = new MemoryStream( bytes ) )
{
    // do your stuff with the stream...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接