验证文件为JPEG [英] Verifying a file is JPEG
本文介绍了验证文件为JPEG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在一个项目中,在该项目中,我使用文件夹对话框查找JPG文件并在列表中列出图像.
现在,我扩展了程序,以便用户可以将文件拖放到列表中.但是我希望图像是JPG.
我检查图像的大小,宽度和高度以及其他,如下所示....
I''m working on a project where I find JPG files using a folder dialog and list the images in a list.
Now, I''ve extended the program so the user can just drag and drop files in the list. But I want the images to be JPG.
I check for image size, width and height, and other as shown below....
public bool IsValid(string FileName)
{
Photo JPGFile = new Photo(FileName);
//Check if the file exists.
if (!System.IO.File.Exists(JPGFile.FullPath)) { return false; }
//Check if the File is a JPG File.
if (System.IO.Path.GetExtension(FileName).ToLower() != ".jpg")
{
//<-------------------------------Need a better validation------------>
return false;
}
//Check if the FilePath Matches any other file in the List.
foreach (Photo Picture in Photos)
{
if (FileName == Picture.FullPath)
{
return false;
}
else
{
continue;
}
}
//Check if the File Size is greater than 450kb.
if (JPGFile.GetRawSize() > 450)
{
return false;
}
//Check if the Height or width of the image is greater than that of the screen size.
if (JPGFile.ImageWidth > SystemParameters.VirtualScreenWidth || JPGFile.ImageHeight > SystemParameters.VirtualScreenHeight)
{
return false;
}
return true;
}
当我进行测试时,我只是将一个desktop.ini文件重命名为Desktop.jpg并通过了验证.任何人都可以帮助我如何真正检查图像是否为有效的jpg文件.
When I was testing, I just renamed a desktop.ini file to Desktop.jpg and it passed validation. Can anyone help please on how I can really check if the image is a VALID jpg file.
Thanks.
推荐答案
最简单的方法是将其作为图像打开,并在打开时检查其为JPG类型.但是,如果不是,那么您将获得一个异常,该异常可能并不总是可以捕获的.
一种更安全的方法是将文件作为二进制流打开,并检查开始和结束:JPG文件以两个字节0xFF和0xD8开始,并以两个字节0xFF和0xD9结尾. JPG文件中还有一些特定的ASCII字符串: http://en.wikipedia.org/wiki/Magic_number_ %28programming%29#Magic_numbers_in_files [ ^ ]
如果存在这些内容,则可能是JPG.但是唯一可以确定的唯一真实方法是将其作为图像加载!
The easiest way is to open it as an image and check it''s a JPG type when it''s open. However, if it isn''t then you will get an exception which may not always be catchable.
A safer way is to open the file as a binary stream and check the start and end: JPG files start with the two bytes 0xFF and 0xD8, and end with the two bytes 0xFF and 0xD9. There are also some specific ASCII strings in JPG files: http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_numbers_in_files[^]
If these are present, it probably is a JPG. But the only true way to be absolutely sure is to load it as an image!
尝试以下操作:
try this:
public bool IsJpegImage(string filename)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (OutOfMemoryException)
{
return false;
}
}
这篇关于验证文件为JPEG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文