Search code examples
c#asp.netimage-resizingimage-uploadingaspect-ratio

How to keep aspect ratio of image when resizing during upload using asp:FileUpload (ASP.NET - C#)


this is my aspx code:

<asp:FileUpload ID="FileUpload2" runat="server" Width="500px" />
            <asp:Button ID="btnUploadImg" runat="server" onclick="btnNahrajObrazek_Click" Text="Nahrát obrázek" Height="35px" Width="150px" />

and this is my code behind:

protected void btnUploadImg_Click(object sender, EventArgs e)
    {
        string input = Request.Url.AbsoluteUri;
        string output = input.Substring(input.IndexOf('=') + 1);
        string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);

        int width = 800;
        int height = 600;
        Stream stream = FileUpload2.PostedFile.InputStream;

        Bitmap image = new Bitmap(stream);

        Bitmap target = new Bitmap(width, height);
        Graphics graphic = Graphics.FromImage(target);
        graphic.DrawImage(image, 0, 0, width, height);
        target.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
    }

I'd like to keep aspect ratio of images being uploaded, so I need to set only width or set width like 100% and height 400 or something like that ? But don't know to do it.

If this is not possible, image cropping will be good enought, but I'd like first better.

Thanks in advance!


Solution

  • So here is my solution based on what I've found here: http://www.nerdymusings.com/LPMArticle.asp?ID=32

    string input = Request.Url.AbsoluteUri;
            string output = input.Substring(input.IndexOf('=') + 1);
            string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
    
            Stream stream = FileUpload2.PostedFile.InputStream;
    
            Bitmap sourceImage = new Bitmap(stream);
    
            int maxImageWidth = 800;
    
            if (sourceImage.Width > maxImageWidth)
            {
                int newImageHeight = (int)(sourceImage.Height * ((float)maxImageWidth / (float)sourceImage.Width));
                Bitmap resizedImage = new Bitmap(maxImageWidth, newImageHeight);
                Graphics gr = Graphics.FromImage(resizedImage);
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.DrawImage(sourceImage, 0, 0, maxImageWidth, newImageHeight);
                // Save the resized image:
                resizedImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
            }
            else
            {
                sourceImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
            }
    

    It's simple enought and effective, I think.