Sometimes we need to save an image with a different size that it originally had.
As we discussed earlier, the Save method of the Image class is used to save
images. This method also allows us to specify the size of a saved image.
To make our program even more interesting, we will determine the size of the
saved image at runtime. Create a Windows application and add two text boxes, two
tables, and a button control to the form. The text boxes are used to specify the
height and width of the saved images, and the button is used to save the image
with the new size, as shown in Figure 7.42.
First we specify an Image private variable:
Then we create and view the image at the form's paint event handler, as shown in
Listing 7.28.
FIGURE 7.42: Saving images with different sizes
LISTING 7.28: Viewing an image
private void
Form1_Paint(object sender,
PaintEventArgs e)
{
curImage = Image.FromFile("roses.jpg");
e.Graphics.DrawImage(curImage, AutoScrollPosition.X,
AutoScrollPosition.Y, curImage.Width, curImage.Height);
}
private void
SaveImageBtn_click(object sender, System.EventArgs
e)
{
if (curImage ==
null)
return;
int height =
Convert.ToInt16(textBox1.Text);
int width =
Convert.ToInt16(textBox1.Text);
SaveFileDialog saveDlg =
new SaveFileDialog();
saveDlg.Title = "save Image As";
saveDlg.OverwritePrompt = true;
saveDlg.CheckPathExists = true;
saveDlg.Filter =
"Bitmap File (*.bmp) | .bmp | Gif File
(.gif) | *.gif | " +
"JPEG File (*.jpg) | *.jpg";
saveDlg.ShowHelp = true;
if (saveDlg.ShowDialog() ==
DialogResult.OK)
{
string fileName =
saveDlg.FileName;
string extn =
fileName.Substring(fileName.Length - 3, 3);
Bitmap newImage =
new Bitmap(curImage,
new
Size(width, height));
if (extn.Equals("bmp"))
newImage.Save(fileName, ImageFormat.Bmp);
else if
(extn.Equals("gif"))
newImage.Save(fileName, ImageFormat.Gif);
else if
(extn.Equals("jpg"))
newImage.Save(fileName, ImageFormat.Jpeg);
}
}