I have a C# function to REsize images.The parameters of the funciton would be orginal image path,new image path(path after saving the resizing of image). Now i want to build a logic for the below requirement.
1 . If the orginal file's width is greater than 480 or lessthan 450 ,then i want to set the width of output image as 450px.and the height has to be proportional of the width.
- If the width of the orginal file is > its height, then add white space to the top and to bottom (to the height) so that the new height will be 650.
I m using the follwing code to resize image
try
{
Size oldSize=new Size();
Bitmap oldbmp1 = (Bitmap) Bitmap.FromFile(originalpath);
oldSize.Width=oldbmp1.Width;
oldSize.Height=oldbmp1.Height;
Size newSize=new Size()
using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(originalpath) as Bitmap)
{
Graphics newgraphics = Graphics.FromImage(newbmp);
newgraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// newsize = GetNewImageSize(oldSize); // here i want the new Size
newgraphics.Clear(Color.FromArgb(-1));
newgraphics.FillRectangle(Brushes.White, 0, 0, newsize.Width, newsize.Height);
newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
try
{
// newgraphics.Save();
ImageCodecInfo[] Info = ImageCodecInfo.GetImageEncoders();
EncoderParameters Params = new EncoderParameters(1);
Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
newbmp.Save(newpath, Info[1], Params);
}
catch (Exception ex1)
{
throw ex1;
}
finally
{
newbmp.Dispose();
oldbmp.Dispose();
oldbmp1.Dispose();
}
}
}
catch (Exception ee)
{
throw ee;
}
Can any one advice what else i have to add on this ?
EDIT (Since comment field will not allow me to have more characters)
I tried this
float ratio = oldImg.Width / oldImg.Height;
SizeF newSize = new SizeF(desiredWidth, desiredWidth * ratio);
But it will not worked as i wish Ex : My orginal image had width 450 and height 1094. So ratio=450/1094 which is 0.4113; Desired height=desired width * ratio ie ; 450*0.4113 which is 185 .1
How its proportional . I think some thing has to be corrected.Any more thoughts ?
Thanks in advance