1

I want to do convert image in byte array and pass it to web api to save image on server and image name in database.

I have done following code but getting exception as Parameter is not valid when I am using this block -

byte[] param contains byte array value of image from request url
     using (var ms = new System.IO.MemoryStream(param))
                    {
                        var cd= Image.FromStream(ms);
     //...
                    }

 using (var ms = new System.IO.MemoryStream(param))
                    {
                        var Image= Image.FromStream(ms);
     //...
                    }

I have tried the solutions as I have found in searching but same error occured.

Can anyone help me to resolve this error.

Geetanjali Jain
  • 402
  • 6
  • 19
  • Image.FromStream is to create an image from a stream – Jean-Claude Colette Oct 01 '16 at 10:02
  • Yes I am trying to do so but it throws above mentioned exception. – Geetanjali Jain Oct 01 '16 at 10:05
  • check the number of bytes in param to make sure the size didn't change from source. The method FromStream checks the image to make sure it is valid and will give an exception when the byte array doesn't contain a valid image. Often when I'm solving issues like this I find where the size changes to find root cause of issue. – jdweng Oct 01 '16 at 10:07

1 Answers1

0

It all depends on what param really is:

  1. Raw pixel data?

    You should read this answer.

  2. An image file?

    Your code should work. The error you are getting is probably due to the fact that it is not.

  3. A serialized image?

    In that case, you'd need to use a Binary formatter. You can find one in the System.Runtime.Serialization.Formatters.Binary namespace.

    To get an image from a byte[] buffer you'd do the following:

    Image deserializedImage = null;
    
    using (var memoryStream = new MemoryStream(bytes, false))
    {
        deserializedImage = (Image)formatter.Deserialize(memoryStream);
    }
    

If none of these options work, then you need to investigate how exactly is param generated and the data it contains.

Community
  • 1
  • 1
InBetween
  • 32,319
  • 3
  • 50
  • 90