Thursday, June 22, 2017

Check dimensions and size of image before uploading in

In this article I am going to explain how to check height and width (dimensions) and size of image before uploading in

I want to upload the image which have dimensions less than 100 x 120 and size 20 KB. Firstly I have check the image size with height and width, if image size and dimensions is less than the require dimensions then it will be uploaded.

I am checking image size on both client and server side.

HTML markup:

<html xmlns="">
<head runat="server">
 <script type="text/javascript" >
     function ValidateFilesize() {
         var maxFileSize = 20480;
         var uploadedFile = document.getElementById("<%=FileUpload1.ClientID %>");
         if (uploadedFile.files[0].size > maxFileSize) {
             alert('File size should be less than 20 KB')
             return false;
         return true;
    <form id="form1" runat="server">
            <tr><td>Upload File :</td><td><asp:FileUpload ID="FileUpload1" runat="server" accept=".jpg,.png,.jpeg"/> </td></tr>
            <tr><td></td><td> <asp:Button ID="Button1" runat="server" Text="Save" OnClientClick="return ValidateFilesize();" /></td></tr>

Import the namespace:

C# Code:
using System.Drawing; Code:
Imports System.Drawing

On button click write the below given code:

C# Code:
    protected void Button1_Click(object sender, EventArgs e)
        if (FileUpload1.FileBytes.Length < 20480)
            Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream);
           if(bitmap.Width <100 || bitmap.Height<120)
               string filepath = Server.MapPath("~/images/") + Guid.NewGuid() + FileUpload1.FileName;
               ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Height :" + bitmap.Height + "\\nWidth :" + bitmap.Width + "')", true);
    } Code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If FileUpload1.FileBytes.Length < 20480 Then
            Dim bitmap As New Bitmap(FileUpload1.PostedFile.InputStream)
            If bitmap.Width < 100 OrElse bitmap.Height < 120 Then
                Dim filepath As String = Server.MapPath("~/images/") + Guid.NewGuid().ToString() + FileUpload1.FileName
                ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "alertMessage", "alert('Height :" + bitmap.Height.ToString() + "\nWidth :" + bitmap.Width.ToString() + "')", True)

            End If
        End If

    End Sub

No comments:

Post a Comment