c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
c# .net

How to resize image in asp.net?

| | ASP-NET , CSharp

In this article I will show you how to resize image in asp.net c#. the user selects the image using file upload control and compress and save it in a project specified folder.

Before saving the image compress the Quality, resize and formating.

Compress.aspx:

<form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="fileupload1" runat="server" />
            <asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" />
        </div>
    </form>

Compress.aspx.cs: 

  protected void btnsave_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
        string targetPath = Server.MapPath("Images/" + filename);
        Stream strm = fileupload1.PostedFile.InputStream;
        var targetFile = targetPath;
        //Based on scalefactor image size will vary
        GenerateThumbnails(0.5, strm, targetFile);
    }
 
    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            var newWidth = (int)(image.Width * scaleFactor);
            var newHeight = (int)(image.Height * scaleFactor);
            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);
        }
    }

 

Output: