BLOG.CSHARPHELPER.COM: Resize an image and save the result in C#
Resize an image and save the result in C#
This program lets you load a picture and then scale it. When the form loads, the Load event handler saves the scale factor for each of the scaling menu items in their Tag properties.
// Set the menus' Tag values. private void Form1_Load(object sender, EventArgs e) { picZoom.SizeMode = PictureBoxSizeMode.StretchImage;
This code converts the sender (the menu item clicked) into a ToolStripMenuItem. It gets the item's Tag property and converts it into a numeric scale value.
Next the code sets the client size of the program's PictureBox to the size of the image multiplied by the scale factor. The control automatically assumes the size needed to give it the desired client size plus any borders it may be displaying.
The program uses the following code to save the resized image.
// Make a bitmap of the correct size. using (Bitmap bm = new Bitmap( picZoom.ClientSize.Width, picZoom.ClientSize.Height)) { // Copy the original image onto the new bitmap. using (Graphics gr = Graphics.FromImage(bm)) { Rectangle source_rect = new Rectangle( 0, 0, picZoom.Image.Width, picZoom.Image.Height); Rectangle dest_rect = new Rectangle( 0, 0, bm.Width, bm.Height); gr.DrawImage(picZoom.Image, dest_rect, source_rect, GraphicsUnit.Pixel); }
// Save the bitmap. SaveBitmapUsingExtension(bm, sfdPicture.FileName); }
The code creates a Bitmap of the right size to fit the image's current scaled size and creates a Graphics object associated with the Bitmap. It then creates Rectangles representing the source area (the entire image) and the destination area (the scaled area), and uses the Graphics object's DrawImage method to draw the image on the Bitmap. It finishes by calling the SaveBitmapUsingExtension method to save the Bitmap in the appropriate format.
Comments