Reputation: 3
I'm doing a C# web service soap receiving an image. I send a string contain the byte characters. I transform the string in byte[] and next I world like to create the Bitmap.
The line Bitmap img = new Bitmap(ms);
generate an exception : invalid argument.
I have a in the ms object this error : System.InvalidOperationException
value contain the correct string, imgBytes contain the good number of sell.
public string GetImage(string value)
{
byte[] imgBytes = Encoding.ASCII.GetBytes(value);
MemoryStream ms = new MemoryStream(imgBytes, true);
Bitmap img = new Bitmap(ms);
Thank you for your help.
Upvotes: 0
Views: 943
Reputation: 46
I had a similar problem. Basically you write into your memory stream (in the constructor) and the position pointer is at the end. So before reuse the memory stream you can try setting its position pointer to the beginning. Like this:
MemoryStream ms = new MemoryStream(imgBytes, true);
ms.Position = 0;
Bitmap img = new Bitmap(ms);
or the more general approach:
MemoryStream ms = new MemoryStream(imgBytes, true);
ms.Seek(0, SeekOrigin.Begin);
Bitmap img = new Bitmap(ms);
Hope this will solve your Problem.
Update I think @heinbeinz answer is also important: First decode your string from the right encoding (normally base64), then set the position.
Upvotes: 0
Reputation: 3542
It looks like your string holds base64 encoded data. Try to decode it to a byte array via Convert.FromBase64String
Upvotes: 1