How to resize image in Asp.net?

IntroductionIn this article i will explain with example How to upload image file through file upload control and resize the uploaded image in asp.net using both C#.Net and VB.Net languages.In previous articles i explained How to create thumbnail, small and large version of the uploaded image in Asp.net and How to Validate and upload image files in asp.net and jQuery to validate file extension and upload image file and Bind,upload,download,delete image files from the GridView  and Drag & drop to upload multiple files using AjaxFileUpload like Facebook and Upload and create Zip file and Maintain image on PostBack in FileUpload control


Description: While working on asp.net application it is sometimes required to resize the image as per application requirement. Suppose there is image upload functionality in your website where user can upload their pictures. In this case you must resize the image before storing so that web space requirement for storing can be reduced.

Implementation: Let's understand by creating a demo website.

Source Code:
  • In the design page (.aspx) place a FileUpload Control and a Button control as:
<table>
        <tr>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                      <asp:Button ID="btnUpload" runat="server" Text="Submit"
            onclick="btnUpload_Click" /></td>
         </tr>          
  </table>

C#.NET Code to  upload and resize the images
  • In the code behind file (.aspx.cs) write the code as:
First include following namespaces:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.IO;
  • Then write the code as:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string img=string.Empty;
            Bitmap bmpImg=null;
            try
            {
                bmpImg = Resize_Image(FileUpload1.PostedFile.InputStream, 210, 130);
                img = Server.MapPath("images/") + Guid.NewGuid().ToString() + “.png";
                bmpImg.Save(img, ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                Response.Write("Error occured: " + ex.Message.ToString());
            }
            finally
            {
                img = string.Empty;
                bmpImg.Dispose();
            }      
          }
    }
  

private Bitmap Resize_Image(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height);

        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio));
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio));
        }
        return new Bitmap(originalImage, newWidth, newHeight);
    }


VB.NET Code to resize the images
  • In the code behind file (.aspx.vb) write the code as:
First Import following namespaces:

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Design
Imports System.IO
  • Then write the code as:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        If FileUpload1.HasFile Then
            Dim img As String = String.Empty
            Dim bmpImg As Bitmap = Nothing
            Try
                bmpImg = Resize_Image(FileUpload1.PostedFile.InputStream, 210, 130)
                img = Server.MapPath("images/") + Guid.NewGuid().ToString() + ".png"
                bmpImg.Save(img, ImageFormat.Jpeg)
            Catch ex As Exception
                Response.Write("Error occured: " & ex.Message.ToString())
            Finally
                img = String.Empty
                bmpImg.Dispose()
            End Try
        End If
    End Sub

    Private Function Resize_Image(ByVal streamImage As Stream, ByVal maxWidth As Integer, ByVal maxHeight As Integer) As Bitmap
        Dim originalImage As New Bitmap(streamImage)
        Dim newWidth As Integer = originalImage.Width
        Dim newHeight As Integer = originalImage.Height
        Dim aspectRatio As Double = CDbl(originalImage.Width) / CDbl(originalImage.Height)

        If aspectRatio <= 1 AndAlso originalImage.Width > maxWidth Then
            newWidth = maxWidth
            newHeight = CInt(Math.Round(newWidth / aspectRatio))
        ElseIf aspectRatio > 1 AndAlso originalImage.Height > maxHeight Then
            newHeight = maxHeight
            newWidth = CInt(Math.Round(newHeight * aspectRatio))
        End If

        Return New Bitmap(originalImage, newWidth, newHeight)
    End Function

Note: Uploaded image will be stored in the “images” folder of the root directory in our case. You can change the folder name and location as per your requirement.  Now you can display the resized image on your website.

Now over to you: 
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates." 

Previous
Next Post »

7 comments

Click here for comments
Anonymous
admin
October 01, 2013 ×

some times image not saved.Why?

Reply
avatar
October 01, 2013 ×

This code is completely tested and working code..Can you please mention the case when you are facing this issue?

Reply
avatar
Anil Thakur
admin
December 10, 2013 ×

hello sir,i tried out this code it works fine but only one problem that every image has his own width and height so according to this code we take out the aspect ratio of the image which will be differ for each image so could you tell me that i want to save image in my folder with 960 width and 360 height how could i can do that with any kind of image whether its small or big could you help me sir?

Reply
avatar
Unknown
admin
February 04, 2014 ×

sir plz write an article " upload video in asp.net by using c #"...

Reply
avatar
February 04, 2014 ×

Hello umbreen sabir..thanks for your suggestion..i will create an article as per your requirement and publish very soon..so stay connected and keep reading ...:)

Reply
avatar
Anonymous
admin
March 28, 2014 ×

thanks, nice article. but i need one help. i am trying to preview it in a an image div after saving. so i gave the code imagebuttonname.ImageUrl=img; after the code bmpImg.Save(img, ImageFormat.Jpeg); but the image is not getting preview. kindly help me. i ll be very thankful

Reply
avatar
Anonymous
admin
December 20, 2014 ×

very useful

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..