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.
You can try to generate an image from the byte array and check for the ArgumentException if its not. Show activity on this post. 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.
Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With