1

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!

Morignus
  • 95
  • 1
  • 6
  • 1
    check these links: [http://www.codeproject.com/Articles/191424/Resizing-an-Image-On-The-Fly-using-NET](http://www.codeproject.com/Articles/191424/Resizing-an-Image-On-The-Fly-using-NET) and [http://stackoverflow.com/questions/1940581/c-sharp-image-resizing-to-different-size-while-preserving-aspect-ratio](http://stackoverflow.com/questions/1940581/c-sharp-image-resizing-to-different-size-while-preserving-aspect-ratio) – Guido Preite Apr 08 '13 at 10:58

1 Answers1

2

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.

Morignus
  • 95
  • 1
  • 6