问题
I know there is no .Net function that exists for checking, but is there an algorithm or easy and effective way of checking if a byte is a valid image before I use the byte array. I need this because I'm sending different commands to a server who is constantly listening to the client and one of the commands is to get the screenshot of the server's computer.
回答1:
You can try to generate an image from the byte array and check for the ArgumentException
if its not.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}
回答2:
As noted, trying to load it into an image is the only fail-safe way. You can check the magick number aka file header based on the [expected] image type. For instance, the first 8 octets of a *.PNG file are, in hex:
0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A
http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
Most other types of image files have similar magick numbers.
But checking that won't actually tell you if the file is a valid image file. All you'll know after that is that the magick number seems to indicate that its a file of type X. It could still be truncated or otherwise corrupted, or even be something else entirely that just happens to have the right sequence of octets in the right place.
回答3:
For a JPEG you can check that the first two bytes are 0xFF, 0xD8 and the last two are 0xFF, 0xD9. Of course its still possible that the image data will match the EOI tag, but this should be rare.
回答4:
According to me, if you want only image input(Proper image), then you should go with accept attribute of input field like this:
input type="file" name="uploadedFile" id="imageContent" class="required" accept="image/*"/>
This will give you only images in input. So, you can freely code for backend. Without worrying about the image is valid or not.
And even you can specify specific image type if you want like:
input type="file" name="uploadedFile" id="imageContent" class="required" accept="image/jpeg, image/gif, image/png">
来源:https://stackoverflow.com/questions/8349693/how-to-check-if-a-byte-array-is-a-valid-image