I have this problem when I drag to select region of the image in the picturebox more than two times and run the scanning. This is an OCR system.
region OCR(Tab4_Component)
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
i understand the reason it occur is that the image has been duplicated. But I have no idea how to solve it.
First off this looks like a dublicate of this topic:
c# Bitmap.Save A generic error occurred in GDI+ windows application
You also authored that question. From what I can tell it's the same question regarding the same code.
You mention this happens the second time you select an area, and both time you save the image to the same path. You also say the errors occurs when saving.
I think that would be a very strong indication of a permission error. Have you tried saving to a new file name every time as a test?
If it's a permission error then you simply need to dispose of any resources that have taken a lock on that file.
There are plenty of examples of this out there:
http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/
public void Method1()
{
Image img = Image.FromFile(fileName);
Bitmap bmp = img as Bitmap;
Graphics g = Graphics.FromImage(bmp);
Bitmap bmpNew = new Bitmap(bmp);
g.DrawImage(bmpNew, new Point(0, 0));
g.Dispose();
bmp.Dispose();
img.Dispose();
//code to manipulate bmpNew goes here.
bmpNew.Save(fileName);
}
There could however be other issues. If you get the image from a stream, this stream needs to remain open until you're done with the image. (When you dispose of the image you'll automatically dispose of the stream.)
I can't see anything like that in the code you've posted though.
If you are using a 3rd party library for the OCR part, it could also have taken a lock on the resource.
A good place to read about this would be here:
http://support.microsoft.com/?id=814675
However from all you've said it simply sounds like there's a lock on the file you try to save to. So as mentioned above I would start off by simply trying to give the file a new name each time. If it doesn't work then you can start exploring other possibilities.
Quick and dirty example:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic-" + Guid.NewGuid().ToString() + #".jpg");
You should try this before dismissing a permission issue.
Related
Here is my small software.. We add images clicking "ADD YOUR QR CODE" and it will be displayed on pictureBoxLoad picturebox, After that i will crop the image. Then it shows on picturebox2.
But my problem is ,it is only shows on picturebox2, But picturebox2.image is null...how to fix that error. I want to add cropping image to picturebox2 without null..
here after clicking the crop button
here is the code i tried
{
int xDown = 0;
int yDown = 0;
int xUp = 0;
int yUp = 0;
Rectangle rectCropArea = new Rectangle();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Task timeout;
string fn = "";
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void selectIm_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void PictureBoxLoad_MouseUp(object sender, MouseEventArgs e)
{
}
private void PictureBoxLoad_MouseDown(object sender, MouseEventArgs e)
{
}
private void crop_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter= "Image Files(*.jpg; *.jpeg; *.gif;*.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp;*.png";
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void button2_Click(object sender, EventArgs e)
{
string root = #"C:\FuePass";
// If directory does not exist, create it.
if (!System.IO.Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
}
Bitmap bmp = new Bitmap(previewimg.Width, previewimg.Height);
previewimg.DrawToBitmap(bmp, new Rectangle(0, 0, previewimg.Width, previewimg.Height));
pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - previewimg.Location.X, pictureBox2.Location.Y - previewimg.Location.Y, pictureBox2.Width, pictureBox2.Height));
bmp.Save(#"C:\Fuepass\output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("Saved,Locaiton : C:\\Fuepass\\");
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "JPG(*.JPG)|*.jpg";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// previewimg.Image.Save(dialog.FileName);
// pictureBox2.Image.Save(dialog.FileName);
// }
// }
}
private void PictureBoxLoad_Click(object sender, EventArgs e)
{
}
private void PictureBoxLoad_MouseDown_1(object sender, MouseEventArgs e)
{
PictureBoxLoad.Invalidate();
xDown = e.X;
yDown = e.Y;
crop.Enabled = true;
}
private void PictureBoxLoad_MouseUp_1(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
PictureBoxLoad.CreateGraphics().DrawRectangle(pen, rec);
}
rectCropArea = rec;
crop.Enabled = true;
}
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
//pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
}
}
plz tell me the error
You should be able to set the Image to a Bitmap. But do not dispose the Bitmap before you do the save. Hope this helps.
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
pictureBox2.Image = sourceBitmap;
pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
sourceBitmap.Dispose();
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
Initially I will be loading images(say 20 images) into a picturebox from a specified folder through selection from combobox dropdown, they get loaded normally into the picturebox.
The problem I am facing is when I select the next folder to acquire the image for processing, the previously selected folders images are also displayed in the picturebox after its count only the next folders images are displayed, I am unable to clear the previously loaded images.
To be specific, when I click on a folder from dropdown I want the particular folders image inside the picturebox I don't want the previously loaded images along with them. Am working in VS2013 with c#.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ArrayList alist = new ArrayList();
int i = 0;
int filelength = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(#"C:\Users\Arun\Desktop\scanned");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
}
private void button7_Click(object sender, EventArgs e)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void button8_Click(object sender, EventArgs e)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1;
}
private void button9_Click(object sender, EventArgs e)
{
string selected1 = comboBox1.SelectedItem.ToString();
string selected2 = comboBox2.SelectedItem.ToString();
//Initially load all your image files into the array list when form load first time
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected1, selected2)); //Source image folder path
try
{
if ((inputDir.Exists))
{
//Get Each files
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if (file.Extension == ".tif")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
else if(file.Extension == ".jpg")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
}
pictureBox1.Image = Image.FromFile(alist[0].ToString()); //Display intially first image in picture box as sero index file path
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = 0;
}
}
catch (Exception ex)
{
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
else if(e.KeyCode == Keys.A)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Your code has many issues.
The one you are looking for is that you don't clear the alist before loading new file names.
So insert:
alist.Clear();
before
//Get Each files
And also
filelength = alist.Count;
after the loop. No need to count while adding!
Also note that ArrayList is pretty much depracated and you should use the type-safe and powerful List<T> instead:
List<string> alist = new List<string>();
Of course a class variable named i is silly and you are also relying on always having a SelectedItem in the comboBox2.
And since you are not properly Disposing of the Image you are leaking GDI resources.
You can use this function for properly loading images:
void loadImage(PictureBox pbox, string file)
{
if (pbox.Image != null)
{
var dummy = pbox.Image;
pbox.Image = null;
dummy.Dispose();
}
if (File.Exists(file)) pbox.Image = Image.FromFile(file);
}
It first creates a reference to the Image, then clears the PictureBox's reference, then uses the reference to Dispose of the Image and finally tries to load the new one.
I can't open video in picturebox My code is:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.FileName = "*.*";
if (open.ShowDialog() == DialogResult.OK)
{
isAnyText = false;
// string text = open.FileName;
// MessageBox.Show("resimin yolu :" + text);
/// CvVideoWriter video = new CvVideoWriter();
// videoSource.NewFrame += new NewFrameEventHan
CvCapture capture = new CvCapture(open.FileName);
pictureBox1.Image = new Bitmap(capture);
// pictureBox1.Image = capture;// new Bitmap(pictureBox1.Image);
//pictureBox1.Capture = new Bitmap(open.FileName);
// pictureBox1.Image.
string plaka = ft.GetImageText(open.FileName);
var img = pictureBox1.Image;
}
foreach (var s in ft.textList)
listBox1.Items.Add(s);
}
I have a problem here
pictureBox1.Image = new Bitmap(capture);
At the same time I try this:
pictureBox1.Capture = new Bitmap(open.FileName);
and I try lots of things but I cant do it
Any advance?
I am developing a simple application on face recognition using EmguCv and c#. i am using ms access data to store sample data base. whenever in compile the code i get error "OpenCV: Different sizes of objects" Here is my code.... thanks in ADVANCE.
public partial class Facerecognition : Form
{
EigenObjectRecognizer Recognizer;
private Capture cam;
Image<Bgr, Byte> frame;
Image<Gray, Byte> frame2;
private HaarCascade Haar;
MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
OleDbConnection Connection = new OleDbConnection();
OleDbDataAdapter Adapter;
DataTable Table = new DataTable();
List<string> FaceName = new List<string>();
List<Image<Gray, byte>> FaceImg = new List<Image<Gray, byte>>();
int ConTrain;
string name;
Image result;
public Facerecognition()
{
InitializeComponent();
Haar = new HaarCascade("haarcascade_frontalface_default.xml");
ConnectDatabase();
}
private void button3_Click(object sender, EventArgs e)
{
Traningset t = new Traningset();
t.Show();
}
public void Process(object sender, EventArgs e)
{
frame = cam.QueryFrame();
LoadRecognizer();
pictureBox1.Image = frame.ToBitmap();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void button2_Click(object sender, EventArgs e)
{
cam = new Capture();
Application.Idle += Process;
}
/*public void FaceDetection()
{
frame2 = frame.Convert<Gray, Byte>();
var faces = frame.DetectHaarCascade(Haar, 1.2, 3, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(25, 25))[0];
foreach (var face in faces)
{
frame.Draw(face.rect, new Bgr(Color.Black), 3);
// MessageBox.Show("Face detected " + faces.Length.ToString());
}
}*/
public void ConnectDatabase()
{
Connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=facedatabase.mdb.mdb";
Adapter = new OleDbDataAdapter("Select facename, faceimg from traningset", Connection);
OleDbCommandBuilder CommandBuilder = new OleDbCommandBuilder(Adapter);
Adapter.Fill(Table);
Connection.Open();
if (Table.Rows.Count != 0)
{
int numofrows = Table.Rows.Count;
}
Connection.Close();
}
public Image GetFaceFromDB()
{
Image Fetehedimg;
byte[] fetechedimgbytes = (byte[])Table.Rows[0]["faceimg"];
MemoryStream stream = new MemoryStream(fetechedimgbytes);
Fetehedimg = Image.FromStream(stream);
return Fetehedimg;
}
public void LoadRecognizer()
{
/////////////////////////////////////////////// FACE DETECTER /////////////////////////////////////////////////////
frame2 = frame.Convert<Gray, Byte>();
var faces = frame.DetectHaarCascade(Haar, 1.2, 3, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(25, 25))[0];
foreach (var face in faces)
{
frame.Draw(face.rect, new Bgr(Color.Black), 3);
// MessageBox.Show("Face detected " + faces.Length.ToString());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ConnectDatabase();
Bitmap bitimage;
Image img;
img = new Bitmap(100, 100);
int numofrows=0;
if(Table.Rows.Count!=0)
{
numofrows=Table.Rows.Count;
}
for (int i = 0; i < numofrows; i++)
{
byte[] fetchedBytes = (byte[])Table.Rows[i]["faceimg"];
MemoryStream stream = new MemoryStream(fetchedBytes);
bitimage = new Bitmap(stream);
//bitimage = bitimage.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
FaceImg.Add(new Emgu.CV.Image<Gray, Byte>(bitimage));
String faceName = (String)Table.Rows[i]["facename"];
FaceName.Add(faceName);
}
if (FaceImg.ToArray().Length != 0)
{
MCvTermCriteria termCrit = new MCvTermCriteria(4, 0.001);
Recognizer = new EigenObjectRecognizer(
FaceImg.ToArray(),
FaceName.ToArray(),
3000,
ref termCrit);
MessageBox.Show("face recognized");
// frame.Draw(name, ref font, new Point(faces.rect.X - 2, faces.rect.Y - 2), new Bgr(Color.LightGreen));
}
}
}
}
Uncomment Resize:
for (int i = 0; i < numofrows; i++)
{
byte[] fetchedBytes = (byte[])Table.Rows[i]["faceimg"];
MemoryStream stream = new MemoryStream(fetchedBytes);
bitimage = new Bitmap(stream);
Image<Gray, byte> img = new Emgu.CV.Image<Gray, Byte>(bitimage )
Image<Gray, byte> resizedImage = img.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
FaceImg.Add(resizedImage);
String faceName = (String)Table.Rows[i]["facename"];
FaceName.Add(faceName);
}
You can't perform in Resize in place, that's why the uncommented line was giving you another error:
// not allowed
bitimage = bitimage.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
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
}
Checking folder for new image by file date and change image - working example:
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
}
}
Tested on C#2010Ex .NET 4 Client Profile.