Saturday, April 24, 2010

Resize Image High Quality C#.Net with Size Ratio and File Upload Control

public bool SaveThumbnailImageHQ(System.Web.UI.WebControls.FileUpload fu, string FullSavePath, int HeightMax, int WidthMax)
{
    try
    {
        if (fu.HasFile)
        {
            Size newSize = new Size(WidthMax, HeightMax);
            using (Bitmap bmp = new Bitmap(fu.PostedFile.InputStream))
            {
                double ratioWidth = (double)bmp.Size.Width / (double)newSize.Width;
                double ratioHeight = (double)bmp.Size.Height / (double)newSize.Height;
                double ratio = Math.Max(ratioHeight, ratioWidth);
                int newWidth = (int)(bmp.Size.Width / ratio);
                int newHeight = (int)(bmp.Size.Height / ratio);
                newSize = new Size(newWidth, newHeight);
                using (Bitmap thumb = new Bitmap((System.Drawing.Image)bmp, newSize))
                {
                    using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
                    {
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
                        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                        g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
                        if (System.IO.File.Exists(FullSavePath))
                        {
                            try { System.IO.File.Delete(FullSavePath); }
                            catch { }
                        }
                        thumb.Save(FullSavePath, codec, eParams);
                        //setError(false, string.Empty);
                        return true;
                    }
                }
            }
        }
        else
        {
            //setError(true, "No file input found.");
            return false;
        }
    }
    catch (Exception ex)
    {
        //setError(true, ex.Message);
        return false;
    }
}

1 comment:

  1. there is a cheap alternative that allow to do all resize and compress stuff in just a few clicks right in SharePoint Designer workflow editor. Check out this article: http://www.harepoint.com/Products/HarePointWorkflowExtensions/Example-Images.aspx
    Thanks.

    ReplyDelete