Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a byte array is a valid image?

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.

like image 562
Daniel Lopez Avatar asked Dec 01 '11 23:12

Daniel Lopez


People also ask

How do you check if a byte array is a valid image Java?

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.

How do I find the byte array of an image?

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.

What is byte array format?

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.


1 Answers

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;  } 
like image 167
shf301 Avatar answered Sep 21 '22 12:09

shf301