jeudi 5 novembre 2015

Better Way to Display new Image Document in Picturebox

I'm using WinForms. In my Form i have a picturebox. This program looks in "C:\image\" directory to find a specified image document, in my case a tif file. There is always only one picture in "C:\image\" directory.

After it locates the file, the program displays the image document in the picturebox.

When i was running this i saw that the CPU usage was high. My Goal is to make performance better or find out if there is a better way of coding this.

What i have to do: I have to manually go into my C:\image\ directory and delete the current image document then place a new image document in there so my picturebox will show the new image document.

In short, i have to delete the old image document and replace it with the new one, so i can view the new image document in my picturebox.

   int picWidth, picHeight;

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1_Tick(sender, e);
    }

    private void File_Length()
    {
        try
        {
            string path = @"C:\image\";
            string[] filename = Directory.GetFiles(path, "*.tif"); //gets a specific image doc.

            FileInfo fi = new FileInfo(filename[0]);
            byte[] buff = new byte[fi.Length];
            using (FileStream fs = File.OpenRead(filename[0]))
            {
                fs.Read(buff, 0, (int)fi.Length);
            }
            MemoryStream ms = new MemoryStream(buff);
            Bitmap img1 = new Bitmap(ms);
            //opened = true; // the files was opened.
            pictureBox1.Image = img1;

            pictureBox1.Width = img1.Width;
            pictureBox1.Height = img1.Height;
            picWidth = pictureBox1.Width;
            picHeight = pictureBox1.Height;
        }
        catch(Exception)
        {
            //MessageBox.Show(ex.Message);
        }
    }

    public void InitTimer()
    {
        timer1 = new Timer(); 
        timer1.Tick += new EventHandler(timer1_Tick); //calls method
        timer1.Interval = 2000; // in miliseconds (1 second = 1000 millisecond)
        timer1.Start(); //starts timer
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        File_Length(); //checking the file length every 2000 miliseconds
    }

Aucun commentaire:

Enregistrer un commentaire