0

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);

Code with debug mode

Exception

Thank you for your help.

2 Answers 2

1

It looks like your string holds base64 encoded data. Try to decode it to a byte array via Convert.FromBase64String

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks for you help. The @heinbeinz solution works. I had already saw the ms.Position = 0; but my problem was the decode of the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.