user903550
user903550

Reputation: 81

How to display an image from file system in a PictureBox in WinForm

I have a small doubt regarding loading an image in PictureBox in WinForms.
I want to show an image file from file system in a PictureBox on my form, say form1.

I am doing Windows applications using C#.

I want to check the file type also say is it pdf/text/png/gif/jpeg.
Is it possible to programmatically open a file from file system using C#?
If anyone knows please give any idea or sample code for doing this.

Modified Code: I have done like this for opening a file in my system, but I don't know how to attach the file and attach the file.

 private void button1_Click(object sender, EventArgs e)
 {    
         string filepath = @"D:\";

    openFileDialog1.Filter = "Image Files (*.jpg)|*.jpg|(*.png)|*.png|(*.gif)|*.gif|(*.jpeg)|*.jpeg|";
    openFileDialog1.CheckFileExists = true;
    openFileDialog1.CheckPathExists = true;

    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
    {
        try 
        {


        }        
    }
 }

I don't know what I have to write in try block. Can anyone help on this?

Upvotes: 0

Views: 8886

Answers (2)

      using System.IO;

         openFileDialog1.FilterIndex = 1;
         openFileDialog1.Multiselect = false;        //not allow  multiline selection at the file selection level
         openFileDialog1.Title = "Open Data file";   //define the name of openfileDialog
         openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory


      if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
        {
            try 
            {
               string filename = openFileDialog1.FileName;
               FileStream fs=new FileStream(filename, FileMode.Open, FileAccess.Read); //set file stream
               Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
               fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
               MemoryStream stream = new MemoryStream(bindata);//load picture 
               stream.Position = 0;
               pictureBox1.Image = Image.FromStream(stream);
            }        
        }

Upvotes: 1

Tigran
Tigran

Reputation: 62265

Use Image.ImageFromFile http://msdn.microsoft.com/en-us/library/system.drawing.image.fromfile.aspx method

Image img = Image.ImageFromFile(openFileDialog1.FileName);

Should work.

EDIT

If you're going to set it to PictureBox, and what to see complete inside it, use picturebox

SizeMode property.

Upvotes: 2

Related Questions