In this article I will explain with an example, how to display Byte Array as Image in PictureBox control in Windows Forms (WinForms) Application using C# and VB.Net.
The Image file will be selected from Folder (Directory) using the OpenFileDialog control and then the chosen Image file will be converted to Byte Array and then displayed in PictureBox control in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The below Form consists of a Button, a Label and a PictureBox control.
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Drawing;
VB.Net
Imports System.IO
Imports System.Drawing
Display Byte Array as Image in PictureBox control in Windows Application
When the Choose File Button is clicked, the OpenFileDialog is opened and the Image file is selected.
The selected Image file is first converted to Byte Array and then displayed in PictureBox control using the FromStream function of the Image class.
C#
private void btnChoose_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
lblFileName.Text = Path.GetFileName(openFileDialog1.FileName);
//Read Image File into Image object.
Image img = Image.FromFile(openFileDialog1.FileName);
//ImageConverter Class convert Image object to Byte Array.
byte[] bytes = (byte[])(new ImageConverter()).ConvertTo(img, typeof(byte[]));
//Convert Byte Array to Image and display in PictureBox.
pictureBox1.Image = Image.FromStream(new MemoryStream(bytes));
}
}
}
VB.Net
Private Sub btnChoose_Click(sender As System.Object, e As System.EventArgs) Handles btnChoose.Click
Using openFileDialog1 As OpenFileDialog = New OpenFileDialog()
If openFileDialog1.ShowDialog() = DialogResult.OK Then
lblFileName.Text = Path.GetFileName(openFileDialog1.FileName)
'Read Image File into Image object.
Dim img As Image = Image.FromFile(openFileDialog1.FileName)
'ImageConverter Class convert Image object to Byte Array.
Dim bytes As Byte() = CType((New ImageConverter()).ConvertTo(img, GetType(Byte())), Byte())
'Convert Byte Array to Image and display in PictureBox.
pictureBox1.Image = Image.FromStream(New MemoryStream(bytes))
End If
End Using
End Sub
Screenshot
Downloads