我正在使用WinForms。在我的表格中我有一个图片框。该程序在“C:\ image \”目录中查找指定的图像文档,在我的例子中是一个tif文件。 “C:\ image \”目录中始终只有一张图片。
在找到文件后,程序会在图片框中显示图像文档。
当我运行时,我看到CPU使用率很高。我的目标是提高性能,或者找出是否有更好的编码方式。
我需要做什么:我必须手动进入我的C:\ image \目录并删除当前的图像文档,然后在其中放置一个新图像文档,这样我的图片框就会显示新的图像文件。
简而言之,我必须删除旧的图像文档并将其替换为新的图像文档,这样我才能在我的图片框中查看新的图像文档。
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
}
答案 0 :(得分:1)
按文件日期检查新图像的文件夹并更改图像 - 工作示例:
int picWidth, picHeight;
Timer timer1;
DateTime oldfiledate;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick); //add event
timer1.Interval = 2000; // in miliseconds (1 second = 1000 millisecond)
timer1.Start(); //starts timer
}
private void timer1_Tick(object sender, EventArgs e)
{
ChangeImage(); //call check&change function
}
private void Form1_Load(object sender, EventArgs e)
{
timer1_Tick(sender, e); //raise timer event once to load image on start
InitTimer();
}
private void ChangeImage()
{
string filename = @"c:\image\display.tif";
DateTime filedate = File.GetLastWriteTime(filename);
if (filedate > oldfiledate) // change image only if the date is newer
{
FileInfo fi = new FileInfo(filename);
byte[] buff = new byte[fi.Length];
using (FileStream fs = File.OpenRead(filename)) //read-only mode
{
fs.Read(buff, 0, (int)fi.Length);
}
MemoryStream ms = new MemoryStream(buff);
Bitmap img1 = new Bitmap(ms);
pictureBox1.Image = img1;
pictureBox1.Width = img1.Width;
pictureBox1.Height = img1.Height;
picWidth = pictureBox1.Width;
picHeight = pictureBox1.Height;
oldfiledate = filedate; //remember last file date
}
}
在C#2010Ex.net 4客户端配置文件上测试。