Tuesday, 3 September 2013

Resize an Image in c#

static Stream strm = null;
fileName = FileUpload2.PostedFile.FileName;
strm = FileUpload2.PostedFile.InputStream;
GetHeightWidth_Resize("115","120",fileName);

public void GetHeightWidth_Resize(string Height, string Width, string resizeFileName)
    {
        try
        {
            string filename = resizeFileName;
            string targetPath = Server.MapPath(Request.ApplicationPath) + "\\Worksheet\\" + Convert.ToString(Session["SchoolId"]) + "\\" + filename;
            var targetFile = targetPath;
            ResizeImage(Height, Width, strm, targetFile);           
        }

        catch (Exception ex)
        {
            objException.keepExceptionDetails(PageName, "GetHeightWidth_Resize()", ex.Message);
            Response.Redirect("SisError.aspx");
        }

    }

    private void ResizeImage(string Height, string Width, Stream sourcePath, string targetPath)
    {
        try
        {
            using (var image = System.Drawing.Image.FromStream(sourcePath))
            {
                var newWidth = Convert.ToInt32(Width);
                var newHeight = Convert.ToInt32(Height);
                var thumbnailImg = new Bitmap(newWidth, newHeight);
                var thumbGraph = Graphics.FromImage(thumbnailImg);
                thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbGraph.DrawImage(image, imageRectangle);
                thumbnailImg.Save(targetPath, image.RawFormat);
            }
        }

        catch (Exception ex)
        {
            objException.keepExceptionDetails(PageName, "ResizeImage()", ex.Message);
            Response.Redirect("SisError.aspx");
        }
    }

No comments:

Post a Comment