In object-oriented programming, it's almost a necessity to learn how to convert images into byte arrays. This is required when you work with media applications that import and export images from databases. It is recommended to store an image in a database in a byte data type instead of using an image. In Microsoft Visual C#, you can use the "MemoryStream" class together with the "ImageFormat.Gif" property to make the conversion easily.
- Skill level:
Other People Are Reading
Things you need
- Microsoft Visual C# Express
Open Microsoft Visual C# Express and select "New Project..." from the left pane of your screen. Click "Visual C#" under "Installed Templates" and double-click "Windows Forms Application."
Double-click "PictureBox" to add a picture box control to the form. Add a button using the same technique.
Right-click the "PictureBox" control and click "Properties." Find the "Image" property under Appearance and click the ellipsis to open the Select Resource dialogue window. Click "Import" and browse for a ".BMP" image. Click "Open" and click "OK."
Double-click "button1" to create a click event for the button. Add the following namespace to the very first line of your code module:
Copy and paste the following code to the button click event to convert the ".BMP" image in the picture box into a byte array:
byte byteArray = null;
MemoryStream ms = new MemoryStream(); pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byteArray = ms.ToArray();
Press "F5" to run the program, and click "button1."
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for