Tuesday, March 25, 2014

Image Resize in C#

The below code snippet (adapted from Stackoverflow) will do a image resize to a desired width in pixels. I hope it helps.

/// <summary>
/// Resize image to desired dimension based on width
/// </summary>
/// <param name="strSrcPath">Full absolute path of image source</param>
/// <param name="strDestPath">Full absolute path for resized image to be saved to</param>
/// <param name="iNewWidth">New desired width in pixels</param>
/// <param name="blnIgnoreIfNewWidthLarger">Do not resize image should new desired width is larger than width of original image if set to true</param>
public void Resize(string strSrcPath, string strDestPath, int iNewWidth, bool blnIgnoreIfNewWidthLarger)
{
 bool blnDoNotResize = false;
 System.Drawing.Image objSrcImage;
 System.Drawing.Bitmap objDestImage;
 System.Drawing.Graphics objGrapics;

 try
 {
  objSrcImage = System.Drawing.Image.FromFile(strSrcPath);

  int iSrcWidth = objSrcImage.Width;
  int iSrcHeight = objSrcImage.Height;

  blnDoNotResize = ((iSrcWidth == iNewWidth) || (blnIgnoreIfNewWidthLarger && iNewWidth > iSrcWidth));

  if (!blnDoNotResize)
  {
   int iNewHeight = iSrcHeight * iNewWidth / iSrcWidth;

   int iSrcX = 0, iSrcY = 0, iDestX = 0, iDestY = 0;
   float fPercent = 0, fPercentW = 0, fPercentH = 0;

   fPercentW = ((float)iNewWidth / (float)iSrcWidth);
   fPercentH = ((float)iNewHeight / (float)iSrcHeight);
   if (fPercentH < fPercentW)
   {
    fPercent = fPercentH;
    iDestX = System.Convert.ToInt16((iNewWidth - (iSrcWidth * fPercent)) / 2);
   }
   else
   {
    fPercent = fPercentW;
    iDestY = System.Convert.ToInt16((iNewHeight - (iSrcHeight * fPercent)) / 2);
   }

   int iDestWidth = (int)(iSrcWidth * fPercent);
   int iDestHeight = (int)(iSrcHeight * fPercent);

   objDestImage = new System.Drawing.Bitmap(iNewWidth, iNewHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
   objDestImage.SetResolution(objSrcImage.HorizontalResolution, objSrcImage.VerticalResolution);

   objGrapics = System.Drawing.Graphics.FromImage(objDestImage);
   objGrapics.Clear(System.Drawing.Color.Black);
   objGrapics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

   objGrapics.DrawImage(objSrcImage,
    new System.Drawing.Rectangle(iDestX, iDestY, iDestWidth, iDestHeight),
    new System.Drawing.Rectangle(iSrcX, iSrcY, iSrcWidth, iSrcHeight),
    System.Drawing.GraphicsUnit.Pixel);

   objGrapics.Dispose();

   objSrcImage.Dispose();

   objDestImage.Save(strDestPath);
   objDestImage.Dispose();
  }
  else
  {
   objSrcImage.Dispose();
   System.IO.File.Copy(strSrcPath, strDestPath, true);
  }
 }
 catch (Exception ex)
 {
  throw ex;
 }
 finally
 {
  objSrcImage = null;
  objDestImage = null;
  objGrapics = null;
 }
}

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.