Validate Image dimension when uploading in ASP.Net
When we allow users to upload images to our asp.net application we might require to restrict users to upload images that are greater than a specified dimensions. For example, if we have requirements to restrict users to upload images that are greater than 100X100 dimension we can do it by Custom Validator control and server side validations.
The below code snippet will help us achieving it using BitMap object.
<asp:FileUpload ID="fuFile" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fuFile"
ErrorMessage="File size should not be greater than 100X100." OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
Bitmap bmIP = new Bitmap(fuFile.PostedFile.InputStream);
if (bmIP.Width > 100 | bmIP.Height > 100)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
For the above code to work, we need to include System.Drawing namespace.
|