I\'ve download an image from the Internet and converted to a String (This is not changeable)
Dim Request As System.Net.WebRequest = _
System.Net.WebRequest
Will this work? I have no idea what format your string is in, so some massaging may be necessary.
Dim strAsBytes() as Byte = new System.Text.UTF8Encoding().GetBytes(Text)
Dim ms as New System.IO.MemoryStream(strAsBytes)
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...
}
Converting binary data to a string in the way you have shown will render it useless. You can't pull it pack out. The text encoding hoses it.
You need to use Base64 - like @Marc shows.
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
}