I’m using WinForms. In my Form I have a picture-box that displays image documents. These image documents have many pages. I have an open, next, and previous button on my form. The next button goes forward one page, and the previous button goes back one page in the document that’s opened in the picture-box. I also have labels on my form to indicate how much pages there are, and what page the user is currently viewing.
The problem with my code is when i open large image files into my picture-box, for example documents that has 1200 pages, and click next. The page loads up slow. I want to improve the performance of the code.
How can i make viewing the image documents faster or my code better?
I provided a tif document to test on: http://www.filedropper.com/sampletifdocument5pages
private int int_Current_Page = 0;
private void btnNextImage_Click_1(object sender, EventArgs e)
{
Image image2;
try
{
if (int_Current_Page == Convert.ToInt32(lblNumPages.Text)) // if you have reached the last page it ends here
// the "-1" should be there for normalizing the number of pages
{ int_Current_Page = Convert.ToInt32(lblNumPages.Text); }
else
{
int_Current_Page++; //page increment
using (FileStream stream = new FileStream(@"C:\my_Image_document", FileMode.Open, FileAccess.Read))
{
image2 = Image.FromStream(stream);
Refresh_Image();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnPrevImage_Click_1(object sender, EventArgs e)
{
if (int_Current_Page == 0) // it stops here if you reached the bottom, the first page of the tiff
{ int_Current_Page = 0; }
else
{
int_Current_Page--; // if its not the first page, then go to the previous page
Refresh_Image(); // refresh the image on the selected page
}
}
private void openButton_Click_1(object sender, EventArgs e)
{
Refresh_Image(); //Opens the large image document
}
private void Refresh_Image()
{
Image myImg; // setting the selected tiff
Image myBmp; // a new occurance of Image for viewing
using (FileStream stream = new FileStream(@"C:\my_Image_document", FileMode.Open, FileAccess.Read))
{
myImg = Image.FromStream(stream);
int intPages = myImg.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); // getting the number of pages of this tiff
intPages--; // the first page is 0 so we must correct the number of pages to -1
lblNumPages.Text = Convert.ToString(intPages); // showing the number of pages
lblCurrPage.Text = Convert.ToString(int_Current_Page); // showing the number of page on which we're on
myImg.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, int_Current_Page); // going to the selected page
myBmp = new Bitmap(myImg, pictureBox1.Width, pictureBox1.Height);
pictureBox1.Image = myBmp; // showing the page in the pictureBox1
}
}