“Parameter not valid” exception loading System.Dra

2019-01-04 12:28发布

Why am I getting the exception "Parameter not valid" in my code:

MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

The length of byteArrayIn is 169014. I am getting this exception despite the fact that no value in it is greater than 255.

9条回答
Animai°情兽
2楼-- · 2019-01-04 13:20

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?
查看更多
smile是对你的礼貌
3楼-- · 2019-01-04 13:27

The "parameter is not valid" exception thrown by Image.FromStream() tells you that the stream is not a 'valid' or 'recognised' format. Watch the memory streams, especially if you are taking various offsets of bytes from a file.

// 1. Create a junk memory stream, pass it to Image.FromStream and 
// get the "parameter is not valid":
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);`

// 2. Create a junk memory stream, pass it to Image.FromStream
// without verification:
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms, false, true);

Example 2 will work, note that useEmbeddedColorManagement must be false for validateImageData to be valid.

May be easiest to debug by dumping the memory stream to a file and inspecting the content.

查看更多
冷血范
4楼-- · 2019-01-04 13:29

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);
查看更多
登录 后发表回答