using System.Drawing;
using System.Drawing.Drawing2D;//w means the output size of the image width
public static bool ResizePhoto(string src, string dest, int w)
{
System.Drawing.Image imgTmp = default(System.Drawing.Image);
double sf = 0;
System.Drawing.Bitmap imgFoto = default(System.Drawing.Bitmap);
imgTmp = System.Drawing.Image.FromFile(src);
if ((imgTmp.Width > w))
{
sf = imgTmp.Width / w;
imgFoto = new System.Drawing.Bitmap(w, (int)(imgTmp.Height / sf));
Rectangle recDest = new Rectangle(0, 0, w, imgFoto.Height);
Graphics gphCrop = Graphics.FromImage(imgFoto);
gphCrop.SmoothingMode = SmoothingMode.HighQuality;
gphCrop.CompositingQuality = CompositingQuality.HighQuality;
gphCrop.InterpolationMode = InterpolationMode.High;
gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
}
else
{
imgFoto = (Bitmap)imgTmp;
}
System.Drawing.Imaging.Encoder myEncoder = default(System.Drawing.Imaging.Encoder);
System.Drawing.Imaging.EncoderParameter myEncoderParameter = default(System.Drawing.Imaging.EncoderParameter);
System.Drawing.Imaging.EncoderParameters myEncoderParameters = default(System.Drawing.Imaging.EncoderParameters);
System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
int x = 0;
for (x = 0; x <= arrayICI.Length - 1; x++)
{
if ((arrayICI[x].FormatDescription.Equals("JPEG")))
{
jpegICI = arrayICI[x];
break;
}
}
myEncoder = System.Drawing.Imaging.Encoder.Quality;
myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 60L);
myEncoderParameters.Param[0] = myEncoderParameter;
try
{
imgFoto.Save(dest, jpegICI, myEncoderParameters);
}
catch (Exception ex)
{
throw ex;
}
imgFoto.Dispose();
imgTmp.Dispose();
return true;
}
Wednesday, February 18, 2009
Resize picture function in C#
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment