How To Make Image Editor Tool In C# - Resizing Image

Updated 8/29/2018 - Formatted
 
This is the next article of the 'How to make Image editing tool' project. In the first article we learned how to show or open image file in our C# application with a very professional look.
 
Now in this article we will learn about resizing the image.
 
Design the right panel with the help of a tabcontrol and a DomainUpDown control, so that the user can input a percentage of the original size of image.
 
1.jpg 
 
Put the values 1 to 1000 in domainupdown control
  1. private void BindDomainIUpDown()  
  2. {  
  3.     for (int i = 1; i <= 999; i++)  
  4.     {  
  5.         DomainUpDown1.Items.Add(i);  
  6.     }  
  7.     DomainUpDown1.Text = "100";  
  8. }
We declare the two variables ModifiedImageSize and OriginalImageSize; OriginalImageSize refers to the original width and height of the image and ModifiedImageSize refers to the width and height of the image after the DomainUpDown control's value selection.
  1. private Size OriginalImageSize;  
  2. private Size ModifiedImageSize;  
We can calculate original size of the image like this: 
  1. int imgWidth = Img.Width;  
  2. int imghieght = Img.Height;  
  3. OriginalImageSize = new Size(imgWidth, imghieght);  
And modifiedSize 
  1. private void DomainUpDown1_SelectedItemChanged(object sender, EventArgs e)  
  2. {  
  3.     int percentage = 0;  
  4.     try  
  5.     {  
  6.         percentage = Convert.ToInt32(DomainUpDown1.Text);  
  7.         ModifiedImageSize = new Size((OriginalImageSize.Width * percentage) / 100, (OriginalImageSize.Height * percentage) / 100);  
  8.         SetResizeInfo();  
  9.     }  
  10.     catch (Exception ex)  
  11.     {  
  12.         MessageBox.Show("Invalid Percentage");  
  13.         return;  
  14.     }  
  15. }  
Resizing image
 
2.jpg 
 
Now we have to resize an image according to it's ModifiedImageSize:
  1. private void btnOk_Click(object sender, EventArgs e)  
  2. {  
  3.     Bitmap bm_source = new Bitmap(PictureBox1.Image);  
  4.     // Make a bitmap for the result.  
  5.     Bitmap bm_dest = new Bitmap(Convert.ToInt32(ModifiedImageSize.Width), Convert.ToInt32(ModifiedImageSize.Height));  
  6.     // Make a Graphics object for the result Bitmap.  
  7.     Graphics gr_dest = Graphics.FromImage(bm_dest);  
  8.     // Copy the source image into the destination bitmap.  
  9.     gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1);  
  10.      // Display the result.  
  11.      PictureBox1.Image = bm_dest;  
  12.      PictureBox1.Width = bm_dest.Width;  
  13.      PictureBox1.Height = bm_dest.Height;  
  14.      PictureBoxLocation();  
  15. }  
The Picturebox will show the image after resizing.
 
So this is very easy to do. You can download the source code for better understanding.


Similar Articles