Image Resize And Upload With Dynamic Width And Height Values

We know how to upload an image but in this example, we will supply the width and height values (in pixels) while uploading the image.

Step 1 - Index.aspx page

This is a form with the File Upload control, textboxes for width and height, validation controls, and a button control to handle the events to upload an image.

  1. <fieldset>  
  2.      <legend>Image Resize and Save</legend>  
  3.          <table>  
  4.               <tr>  
  5.                         <td><label>Upload Image:</label></td>  
  6.                         <td><asp:FileUpload runat="server" ID="fupImage" /></td>  
  7.                         <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="fupImage" Display="Dynamic" ForeColor="Red" Font-Size="Small" runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>  
  8.                             <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$" ControlToValidate="fupImage" runat="server" ForeColor="Red" ErrorMessage="Only jpg, png and gif formats allowed." Display="Dynamic" />  
  9.                         </td>  
  10.                     </tr>  
  11.                     <tr>  
  12.                         <td><label>Image Width:</label></td>  
  13.                         <td><asp:TextBox ID="txtWidth" runat="server" placeholder="Enter width" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></asp:TextBox>  
  14.                         </td>  
  15.                         <td>  
  16.                             <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtWidth" Display="Dynamic" ForeColor="Red" Font-Size="Small" runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>  
  17.                         </td>  
  18.                     </tr>  
  19.                     <tr>  
  20.                         <td>  
  21.                             <label>Image Height:</label></td>  
  22.                         <td>  
  23.                             <asp:TextBox ID="txtHeight" runat="server" placeholder="Enter Height" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></asp:TextBox>  
  24.                         </td>  
  25.                         <td>  
  26.                             <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtHeight" Display="Dynamic" ForeColor="Red" Font-Size="Small" ErrorMessage="Required"></asp:RequiredFieldValidator>  
  27.                         </td>  
  28.                     </tr>  
  29.                     <tr>  
  30.                         <td></td>  
  31.                         <td>  
  32.                             <asp:Button runat="server" ID="btnUpload" Text="Resize & Upload" OnClick="btnUpload_Click" />  
  33.                         </td>  
  34.                     </tr>  
  35.                     <tr>  
  36.                         <td colspan="3">  
  37.                             <asp:Label runat="server" ID="lblResult" ForeColor="Red" Font-Size="Small" Font-Bold="true"></asp:Label></td>  
  38.                     </tr>  
  39.                 </table>  
  40.             </fieldset>  

Step 2 - Index.aspx.cs file

Here is the C# code snippet for image resizing with dynamic width and height values on a button-click event.

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2.         {  
  3.             string newFile = string.Empty;  
  4.             if (fupImage.HasFile)  
  5.             {  
  6.                 int width = Convert.ToInt32(txtWidth.Text);  
  7.                 int height = Convert.ToInt32(txtHeight.Text);  
  8.                 Stream inp_Stream = fupImage.PostedFile.InputStream;  
  9.                 using (var image = System.Drawing.Image.FromStream(inp_Stream))  
  10.                 {  
  11.                     Bitmap myImg = new Bitmap(width, height);  
  12.                     Graphics myImgGraph = Graphics.FromImage(myImg);  
  13.                     myImgGraph.CompositingQuality = CompositingQuality.HighQuality;  
  14.                     myImgGraph.SmoothingMode = SmoothingMode.HighQuality;  
  15.                     myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  16.                     var imgRectangle = new Rectangle(0, 0, width, height);  
  17.                     myImgGraph.DrawImage(image, imgRectangle);  
  18.                     string ext = string.Empty;  
  19.                     ext = System.IO.Path.GetExtension(fupImage.FileName.ToString()).ToLower();  
  20.                     newFile = DateTime.Now.ToString("ddMMyyyyhhmmsstt") + "_" + width + "X" + height + ext;  
  21.                     // Save the file   
  22.                     var path = Path.Combine(Server.MapPath("~/ResizedImages"), newFile);  
  23.                     myImg.Save(path, image.RawFormat);  
  24.                     lblResult.Text = "Image resized and saved in folder 'ResizedImages' successfully";  
  25.                     lblResult.ForeColor = Color.Green;  
  26.                     txtWidth.Text = txtHeight.Text = "";  
  27.                 }  
  28.             }  
  29.             else  
  30.             {  
  31.                 lblResult.Text = "please upload image";  
  32.             }  
  33.         }  

Here is the VB code snippet for image resize with given width and height values on the button-click event.

Index.aspx.vb file

  1. Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click  
  2.         Dim newFile As String = String.Empty  
  3.         If (fupImage.HasFile) Then  
  4.             Dim width As Integer = txtWidth.Text  
  5.             Dim height As Integer = txtHeight.Text  
  6.             Dim inp_Stream As Stream = fupImage.PostedFile.InputStream  
  7.             Using image = System.Drawing.Image.FromStream(inp_Stream)  
  8.                 Dim myImg As Bitmap = New Bitmap(width, height)  
  9.                 Dim myImgGraph As Graphics = Graphics.FromImage(myImg)  
  10.                 myImgGraph.CompositingQuality = CompositingQuality.HighQuality  
  11.                 myImgGraph.SmoothingMode = SmoothingMode.HighQuality  
  12.                 myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic  
  13.                 Dim imgRectangle = New Rectangle(0, 0, width, height)  
  14.                 myImgGraph.DrawImage(image, imgRectangle)  
  15.                 Dim ext As String = String.Empty  
  16.                 ext = System.IO.Path.GetExtension(fupImage.FileName.ToString()).ToLower()  
  17.                 newFile = DateTime.Now.ToString("ddMMyyyyhhmmsstt") & "_" & width & "X" & height & ext  
  18.                 Dim path = System.IO.Path.Combine(Server.MapPath("~/ResizedImages"), newFile)  
  19.                 myImg.Save(path, image.RawFormat)  
  20.                 lblResult.Text = "Image resized and saved in folder 'ResizedImages' successfully"  
  21.                 lblResult.ForeColor = Color.Green  
  22.                 txtWidth.Text = String.Empty  
  23.                 txtHeight.Text = String.Empty  
  24.             End Using  
  25.         Else  
  26.             lblResult.Text = "Please upload image"  
  27.         End If  
  28.     End Sub  

Run the page in the browser to see results.

Image Resize And Upload With Dynamic Width And Height Values 

Upload an image and pass the desired width, height values. Hit the "Resize and Upload" button to see the results. Open the ‘ResizedImages’ folder in your project.

Image Resize And Upload With Dynamic Width And Height Values 
Hurray, the image is resized successfully in the desired dimensions. 

Summary

In this article, I discussed how to resize the image using the Stream class. It can be useful if we need different dimensions for images to be uploaded on our website. Here, we passed dynamic values for width and height. If we want the image to be of a particular dimension, we can make it statically from the code behind.