Why have you converted binary (image) data to a string? This makes no sense... unless you are using base-64?
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))
?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
(edit)
I should add that to work with base-64, simply get the data as a byte[]
, then call Convert.ToBase64String(...)
; and to get back the array, just use Convert.FromBase64String(...)
.
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[]
, so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClient
might make this simpler, as it exposes byte[]
functionality directly:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Stream
approach, here's how to encode and decode the 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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…