Click here to Skip to main content
15,885,914 members
Articles / Web Development

Validate Image Type Using Image GUID in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.67/5 (12 votes)
24 Jun 2012CPOL2 min read 51.1K   309   20  
Vaildate image content using System.Drawing.Image class rather than the image file extension in ASP.NET.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void butSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.HasFile)
            {
                System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.FileContent);
                string FormetType = string.Empty;
                if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid)
                    FormetType = "TIFF";
                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
                    FormetType = "GIF";
                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
                    FormetType = "JPG";
                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
                    FormetType = "BMP";
                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
                    FormetType = "PNG";
                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Icon.Guid)
                    FormetType = "ICO";
                else
                    throw new System.ArgumentException("Invalid File Type");

                lblMessage.Text = "File Formet Is:" + FormetType;
            }
        }
        catch (System.ArgumentException exp)
        {
            lblMessage.Text="Invalid File";
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
            
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I have been working as a Software Engineer on Microsoft .NET Technology.I have developed several web/desktop application build on .NET technology .My point of interest is Web Development,Desktop Development,Ajax,Json,Jquey,XML etc.I have completed Master of Computer Application in May-2011.I'm not happy unless I'm learning something new.

Comments and Discussions