Image.FromStream: Parameter not valid
Asked Answered
P

3

3

I am trying to create an image from a byte array. The byte array is created by a fingerprint scanner (cf CaptureFrame method). fwidth is 256 and fheight is 255.

When I run the code below, I get

System.ArgumentException: Parameter is not valid.

Dim fWidth As Short
Dim fHeight As Short

DFRProxy.DFRProxy.GetImageDimensions(fWidth, fHeight)

Dim imgBufLength As Integer = CInt(fWidth) * fHeight

Dim finger(imgBufLength) As Byte

Dim startCap As Short = DFRProxy.DFRProxy.StartCapture(0)

Dim capFrame As Short = DFRProxy.DFRProxy.CaptureFrame(0, finger, 0)


Using ms As New IO.MemoryStream(finger)
    thisImage = Image.FromStream(ms)
End Using

The error occurs at line

thisImage = Image.FromStream(ms)

The byte array has 65280 elements. I have reviewed several StackOverflow postings that are similar to this, but nothing has worked. I have tried setting the useEmbeddedColorManagement and validateImageData parameters for the FromStream method to False and True, but this does not solve the problem.

Do you have any suggestions on how to correct the ArgumentException?

Practise answered 15/7, 2011 at 20:4 Comment(0)
F
13

FromStream is expecting data in one of these formats:

Managed GDI+ has built-in encoders and decoders that support the following file types:

  • BMP
  • GIF
  • JPEG
  • PNG
  • TIFF

Your byte array I suspect is not in these and does not have the metadata or compression information each of these formats expects.

What you want to do is create a Bitmap object and read through each pixel in the byte array, calling SetPixel in the bitmap for the appropriate pixel. You'll end up with a Bitmap (which is an Image) that has the pixels you want.

Foreignborn answered 15/7, 2011 at 20:16 Comment(4)
Excellent. Thanks. It's a grayscale image. When I use the SetPixel method, how do I convert the grayscale value (0-255) to a system color?Practise
If value is v, new Color(v,v,v) should do the trick (creates a color with equal RGB components, which should be gray)Foreignborn
That did it. Thanks for the excellent answer. It's been driving me crazy for hours.Practise
hey @Practise is there anyway you can share your code here?Selfabuse
C
5

Try the following:

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(byteArray);
Caudad answered 16/6, 2012 at 13:46 Comment(0)
G
0

In addition to >ggsmartboy answer for VB.NET:

On top of module/class/form

Imports system.componentmodel

In the code

Dim ba As New Byte() 'Make sure you set the byte array to something
Dim tc As TypeConverter = TypeDescriptor.GetConverter(GetType(Bitmap))
Dim bmp As Bitmap = tc.ConvertFrom(ba)

And subsequently:

PictureBox1.Image = bmp

Cheers

Giovanna answered 9/2, 2017 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.