Autoadjust images to the width sent by parameter

This function is very useful because it allows you to auto-dimension the images, just sending the image and the width as parameters.

public static Image ResizeImage(Image srcImage, int Width)
{
  int widthImg = srcImage.Width;
  int heigthImg = srcImage.Height;
  int avgImg = (Width * 100)/widthImg;
  int Height = (avgImg * heigthImg)/100;
  
  using (Bitmap imagenBitmap = new Bitmap(Width,Height,PixelFormat.Format32bppRgb))
  {
    imagenBitmap.SetResolution(
    Convert.ToInt32(srcImage.HorizontalResolution),
    Convert.ToInt32(srcImage.HorizontalResolution));
    using (Graphics imagenGraphics = Graphics.FromImage(imagenBitmap))
    {
       imagenGraphics.SmoothingMode = SmoothingMode.AntiAlias;
       imagenGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
       imagenGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
       imagenGraphics.DrawImage(srcImage,new Rectangle(0, 0, Width, Height),
                                new Rectangle(0, 0, srcImage.Width, srcImage.Height),
                                GraphicsUnit.Pixel);
       MemoryStream imagenMemoryStream = new MemoryStream();
       imagenBitmap.Save(imagenMemoryStream, ImageFormat.Jpeg);
       srcImage= Image.FromStream(imagenMemoryStream);
    }
  }
 return srcImage;
}

regards

También te podría gustar...