Validating Sizes of Uploaded Images in ASP.NET

I wanted to share a quick & easy way to validate uploaded images in ASP.NET. One of my projects has a feature allowing users to upload a logo. But I wanted to restrict them to JPG & GIF images, and ensure that the image was within a certain height. So….asp:CustomValidator to the rescue!

Here’s the code for the web page with the INPUT file tag and the CustomValidator:


<INPUT type=”file” id=”txtCorporateLogo” name=”txtCorporateLogo” runat=”server”>

<asp:CustomValidator ID=”valLogo” Runat=server CssClass=”validator”
ErrorMessage=”Logos can only be GIF or JPG images under 100 pixels high”
OnServerValidate=”ValidateLogo” ClientValidationFunction=”checkLogo” ControlToValidate=”txtCorporateLogo”
><br>Logos can only be GIF or JPG images under 100 pixels high</asp:CustomValidator>


Here’s the client-side javascript function that the CustomValidator calls to ensure that we don’t post to the server if the image isn’t a JPG or GIF. The function sets IsValid to true if there’s no file specified, or if it ends with jpg, jpeg, or gif:


<script language="javascript">

		function checkLogo(sender, args)
		{
			var filename = document.getElementById('txtCorporateLogo').value.toLowerCase();
if (filename.length < 1) { args.IsValid = true; } else if (filename.indexOf('.jpg') == -1 && filename.indexOf('.jpeg') == -1 && filename.indexOf('.gif') == -1) { args.IsValid = false; } else { args.IsValid = true; } } </script>

And here’s the server-side method that confirms the image is 100 pixels high or shorter:


        protected void ValidateLogo(object sender, ServerValidateEventArgs args)
        {
            HttpPostedFile imageFile = this.txtCorporateLogo.PostedFile;

            if (imageFile.FileName == String.Empty)
            {
                args.IsValid = true;
            }
            else if (!imageFile.FileName.ToLower().EndsWith(“jpg”) && !imageFile.FileName.ToLower().EndsWith(“gif”))
            {
                args.IsValid = false;
            }
            else
            {
                System.Drawing.Bitmap bitmap = new Bitmap(imageFile.InputStream);

                if (bitmap.Height > 100)
                    args.IsValid = false;
                else
                    args.IsValid = true;

                bitmap.Dispose();

                imageFile.InputStream.Position = 0;    // reset the position in the stream
            }
        }


That’s it. Just remember to check Page.IsValid in your submit method before doing anything with the image.

And I’m starting to get annoyed with FTB’s code import. Look at that mess above! 🙂

0