4

In C#.NET 4.0, based on a problem I had with downloading false images (saving an error aspx page as image.jpg instead of an actual image in image.jpg), I need to somehow read the file and identify if it is a valid image or not. I just need 1 function public bool IsValidJpgImage(string ImageFilename); Anything that returns false (is not a valid image file) I will delete from the disk.

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327

2 Answers2

6

As far I as I know all JPEGs begin internally with same 10 character ASCII string although I can't remember what the first 6 characters are. This is quick/dirty method of indentifying a jpeg image even if the file extension is wrong.

grep -P '^......JFIF' ./'raccoon paint.jpeg'

If the image is not a jpeg the match will fail.

Sirko
  • 72,589
  • 19
  • 149
  • 183
Santana
  • 76
  • 1
  • 1
1

This code is for taking less then 500kb size and .jpg format before upload image

protected void btnOk_Click(object sender, EventArgs e)
{
    long maxsize = 512000;
    string str = Path.GetFileName(FileUpload1.FileName);
    int filesize = FileUpload1.PostedFile.ContentLength;
    string fileexe = Path.GetExtension(FileUpload1.FileName);
    if (filesize <= maxsize )
    {
        if (fileexe == ".jpg" || fileexe == ".jpeg")
        {
            FileUpload1.SaveAs(Server.MapPath("~/Image/" + str));
        }
        else
        {
            lblMsg.Text = "Image extension must be jpg or jpeg";
        }
    }
    else
    {
        lblMsg.Text = "File size is too large.";
    }

}