Question

How do I get a byte array to a picturebox.image?

Asked by: B178

I want to move a byte array to a picturebox.image in VB.NET.

I have a machine vision application that calculates an image.  The calculations are mathematical and I need to display my calculated array on the screen.  I can do it brute force with a loop around the pixelset method:

image1.SetPixel(x, y, Color.FromArgb(255, red, green, blue))

But I need much better performance.  I have been trying to stream my bytes from a byte array, but I can't get past the error: "AgumentException was unhandled" for the line:

Drawing.Image.FromStream(memoryStream)  (see code snippet)

It seems that Image.FromStream() will not accept a MemoryStream as a Stream.  I'm new at VB.NET (an old VB6 guy trying to get with it) and I'm not sure I understand the difference between a Stream and a MemoryStream.

I have also tried to load a Stream from a byte array, but I can't seem to even get started.  I have problems when I try to instanciate the Stream (again my VB6 background has me crippled).  

Thanks,

ImageSize = 3 * CurCamera.WindowXSize * CurCamera.WindowYSize
Dim ms As New MemoryStream(ImageSize)
  .....Code to Dim FrameBug1() as Byte   and to fill FrameBuf1() with data ......
Dim image1 As New Drawing.Bitmap(CurCamera.WindowXSize, Camera.WindowYSize, _ Imaging.PixelFormat.Format24bppRgb)
image1 = Image.FromStream(ms)
Picture1.Image = image1

                                  
1:
2:
3:
4:
5:
6:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-28 at 19:34:20ID24608300
Tags

data array

,

image

,

stream

,

memorystream

,

VB.NET

Topics

Microsoft Visual Basic.Net

,

Photos & Graphics Software

,

Measurement Industry

Participating Experts
2
Points
400
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. create byte array in vb.net
    newbie question, how do i create a char array in vb.net. i'm translating the following code to vb and am able to create an unsigned int array in vb, but not a char array with hex bytes as shown in the last line of the following example. // c code unsigned int ar0[11] = {5...
  2. Byte Array to String in VB
    I read in an array of bytes off the network. I need to be able to split it into an array of strings. This works fine when using system.text.encoding.ASCII, except that some of the characters are greater then 127 (they're data bytes, not string bytes) but ASCII strips them off...
  3. byte array to string
    i am writing a tcp listener that grabs everything coming across port 1000 what i need it to do is grab the packet and read bytes 6 - 10 --- i had it working with winsock in vb6 but cant get it to work in vb.net -- not sure how to convert the byte array (no copy memory method...
  4. PhysicalDrive0 in VBNET
    Hi, I am currently transposing my software from VB6 to VBNET. Most of the time I can struggle through reading manuals, searching the web etc. However i have a problem with some Hard Drive utilities I need to convert. I use the CreateFile/ReadFile using PhysicalDrive* as as ...
  5. passing byte array from VC++ .NET dll to VB.NET
    I am writing a vc++ .Net dll, and this dll will be used under vb.Net. The function in vc++ would be look like: int _stdcall AbcCapData(char * pkt_data) {...} I wish to fill bytes in pkt_data that is going to be used in vb.net. I searched the EE site and found a similar qu...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: JackOfPHPosted on 2009-07-29 at 05:46:20ID: 24969541

Ok try this one:

Dim FrameBug1() as byte

..... Your code here to feel the byte array with data....

Dim ms as New MemoryStream(FrameBug1)
Picture1.image = image.FromStream(ms)

Cheers,

Joseph

 

by: TheLearnedOnePosted on 2009-07-29 at 07:07:10ID: 24970318

It doesn't look like you are writing any bytes to the MemoryStream to create an image from...

 

by: B178Posted on 2009-07-29 at 09:25:01ID: 24971831

The error I get is "ArgumentException was unhandled", "Parameter is not valid" on the line:

Picture1.image = image.FromStream(ms)

I checked the FrameBuf1 array; it has data and has an upperbound of 2359296.

 

by: TheLearnedOnePosted on 2009-07-29 at 11:34:31ID: 24973121

How does the FrameBuf1 array get filled?  Is it valid image bytes?

 

by: B178Posted on 2009-07-29 at 12:16:39ID: 24973548

The array is filled by an 24 bit RGB USB camera.  In VB6 I put a BITMAPINFOHEADER on the front of FrameBuf1 and put it up on the screen with StretchDIBits.  To make sure I have valid data (if not an image) I used the code in the snippet below to put FrameBuf1 up on the screen (albiet very slowly).  

Right now, my goal is to move the data quickly from a frame grab to the display in an effort to get a critical part of my software running in VB.NET.  In the actual application the image will be processed before it is presented.

Thank you for your effort, I really appeciate the help.

'' Loop through the images pixels to reset color.
   i = 0
   For y = 0 To CurCamera.WindowYSize - 1
      For x = 0 To CurCamera.WindowXSize - 1
         red = FrameBuf1(i)
         green = FrameBuf1(i + 1)
         blue = FrameBuf1(i + 2)
         image1.SetPixel(x, y, Color.FromArgb(255, red, green, blue))
         i = i + 3
      Next
   Next
   '' Set the PictureBox to display the image.
   Picture1.Image = image1
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: TheLearnedOnePosted on 2009-07-29 at 14:15:26ID: 24974777

I don't believe that you need to use SetPixel, but you need a valid image in the byte array before you construct a MemoryStream from the byte array.

Example which uses a byte array to create a MemoryStream.  The Using block calls the MemoryStream.Dispose method to release resources after you are done with the stream.

Using stream As New MemoryStream(frameBuffer)
End Using

 

by: B178Posted on 2009-07-29 at 15:18:48ID: 24975267

I know the SetPixel effort is not the way to go.  I just tried that to see if the FrameBuf1 array was a was what I thought it was.  It is.  You asked if it was a valid image... I think the answer is yes, but maybe I'll play with that idea a bit and see if I can construct an array from an image/bitmap and then feed it into a stream.  Maybe that is the instruction I need.  Do you think the BITMAPINFOHEADER needs to be on the front of the data array?  I'll give that some time, but I think...

My problem has to do with the proper use of Streams.  I can not seem to create a stream from an array and then send it through to an image.  The problem isn't that the image is corrupted, but rather that the Image.FromStream(ms) fails because the ms parameter is somehow invalid.

 

by: TheLearnedOnePosted on 2009-07-29 at 15:41:21ID: 24975411

The Bitmap class does not work with DIBs (Device Independent Bitmap).   You would need to convert the DIB to a Bitmap.

There is one possibility (untested):

http://www.taotekaching.com/post/2009/01/08/Device-Independent-Bitmaps-C-and-Meae282acc2a6REDUX!.aspx


Converted from C#:

' Source: 
' http://www.taotekaching.com/post/2009/01/08/Device-Independent-Bitmaps-C-and-Meae282acc2a6REDUX!.aspx 
 
Imports System
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Imports System.IO
 
Public Class DIBConverter
 
    ' our BITMAPINFOHEADER struct, as per gdi 
    ' use LayoutKind to make sure data is marshalled as we've laid it out 
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure BITMAPINFOHEADER
        Public biSize As UInteger
        Public biWidth As Integer
        Public biHeight As Integer
        Public biPlanes As UShort
        Public biBitCount As UShort
        Public biCompression As UInteger
        Public biSizeImage As UInteger
        Public biXPelsPerMeter As Integer
        Public biYPelsPerMeter As Integer
        Public biClrUsed As UInteger
        Public biClrImportant As UInteger
    End Structure
 
    Public Shared Function BitmapFromDIB(ByVal dib As MemoryStream) As Bitmap
        ' get byte array of device independent bitmap 
        Dim dibBytes As Byte() = dib.ToArray()
 
        ' get the handle for the byte array and "pin" that memory (i.e. prevent 
        ' garbage collector from gobbling it up right away)... 
        Dim hdl As GCHandle = GCHandle.Alloc(dibBytes, GCHandleType.Pinned)
 
        ' marshal our data into a BITMAPINFOHEADER struct per Win32 
        ' definition of BITMAPINFOHEADER 
        Dim dibHdr As BITMAPINFOHEADER = DirectCast(Marshal.PtrToStructure(hdl.AddrOfPinnedObject(), GetType(BITMAPINFOHEADER)), BITMAPINFOHEADER)
        Dim is555 As Boolean = True
 
        Dim bmp As Bitmap = Nothing
 
        If dibHdr.biBitCount = 8 Then
            ' set our pointer to end of BITMAPINFOHEADER 
            Dim jumpTo As Int64 = hdl.AddrOfPinnedObject().ToInt64() + dibHdr.biSize
            bmp = New Bitmap(dibHdr.biWidth, dibHdr.biHeight, PixelFormat.Format8bppIndexed)
            bmp.SetResolution((100.0F * CSng(dibHdr.biXPelsPerMeter)) / 2.54F, (100.0F * CSng(dibHdr.biYPelsPerMeter)) / 2.54F)
 
            ' set the colors in our palette 
            Dim palette As ColorPalette = bmp.Palette
            Dim ptr As IntPtr = IntPtr.Zero
            Dim colors As Integer = CInt((dibBytes.Length - (bmp.Width * bmp.Height) - dibHdr.biSize))
            For i As Integer = 0 To 255
                ptr = New IntPtr(jumpTo)
                Dim bmiColor As UInteger = CUInt(Marshal.ReadInt32(ptr))
                Dim r As Integer = CInt(((bmiColor And &HFF0000) >> 16)), g As Integer = CInt(((bmiColor And &HFF00) >> 8)), b As Integer = CInt(((bmiColor And &HFF)))
                palette.Entries(i) = Color.FromArgb(r, g, b)
                jumpTo += 4
            Next
            bmp.Palette = palette
 
            ' now write the remaining bmp data to our bitmap 
            Dim _8bd As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.[WriteOnly], PixelFormat.Format8bppIndexed)
            jumpTo -= hdl.AddrOfPinnedObject().ToInt64()
            Marshal.Copy(dibBytes, CInt(jumpTo), _8bd.Scan0, _8bd.Stride * _8bd.Height)
            bmp.UnlockBits(_8bd)
        ElseIf (dibHdr.biBitCount = 16) AndAlso (dibHdr.biCompression = 3) Then
            Dim jumpTo As Int64 = dibHdr.biClrUsed * CUInt(4) + dibHdr.biSize
            Dim ptr As New IntPtr(hdl.AddrOfPinnedObject().ToInt64() + jumpTo)
            Dim redMask As UShort = CUShort(Marshal.ReadInt16(ptr))
            ptr = New IntPtr(ptr.ToInt64() + (2 * Marshal.SizeOf(GetType(UInt16))))
            Dim greenMask As UShort = CUShort(Marshal.ReadInt16(ptr))
            ptr = New IntPtr(ptr.ToInt64() + (2 * Marshal.SizeOf(GetType(UInt16))))
            Dim blueMask As UShort = CUShort(Marshal.ReadInt16(ptr))
 
            is555 = ((redMask = &H7C00) AndAlso (greenMask = &H3E0) AndAlso (blueMask = &H1F))
        End If
 
        ' go ahead and release the "pin" from our handle on that memory 
        hdl.Free()
 
        ' If the target device does not have one plane, or we're working with a bitmap other 
        ' than a non-compressed (BI_RGB) bitmap, we're not gonna work woith it 
        If dibHdr.biPlanes <> 1 OrElse (dibHdr.biCompression <> 0 AndAlso dibHdr.biCompression <> 3) Then
            Return Nothing
        End If
 
        If bmp Is Nothing Then
            ' we need to know beforehand the pixel-depth of our bitmap 
            Dim fmt As PixelFormat = PixelFormat.Format24bppRgb
 
            Select Case dibHdr.biBitCount
                Case 32
                    fmt = PixelFormat.Format32bppRgb
                    Exit Select
                Case 24
                    fmt = PixelFormat.Format24bppRgb
                    Exit Select
                Case 16
                    fmt = IIf(is555, PixelFormat.Format16bppRgb555, PixelFormat.Format16bppRgb565)
                    Exit Select
                Case Else
                    Return Nothing
            End Select
 
            ' prepare for our output bitmap 
            bmp = New Bitmap(dibHdr.biWidth, dibHdr.biHeight, fmt)
 
            ' load our "empty" bitmap into memory and lock it for 
            ' writing in the format we specified 
            Dim bd As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.[WriteOnly], fmt)
 
            ' marshal our device independent bitmap data over to our output bitmap 
            Marshal.Copy(dibBytes, Marshal.SizeOf(dibHdr), bd.Scan0, bd.Stride * bd.Height)
 
            ' we're done marshalling, so release our bitmapdata lock 
 
            bmp.UnlockBits(bd)
        End If
 
        If dibHdr.biHeight > 0 Then
            ' DIB data is upside-down for some reason, so flip it 
            bmp.RotateFlip(RotateFlipType.RotateNoneFlipY)
        End If
 
        ' return our bitmap 
        Return bmp
    End Function
End Class

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:

Select allOpen in new window

 

by: B178Posted on 2009-08-12 at 06:23:10ID: 25078424

This is a good suggestion.  I'm trying it out, but I have another project that is slowing my efforts.  I'll be back on it soon.  Please keep watching.

 

by: B178Posted on 2009-09-15 at 05:34:39ID: 25334125

I'm sorry for the long delay in trying the latest offered solution.  I believe it will take me another 2 weeks to provide my next comment.  Please be patient.  I've been distracted by another project and will be back to this one soon.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...