package de.gurkengewuerz.termbin.Utils; import java.util.Arrays; public class ImageUtils { static byte[] PNG_HEADER = hexStringToByteArray("89504e470d0a1a0a"); /** * Check if the image is a PNG. The first eight bytes of a PNG file always * contain the following (decimal) values: 137 80 78 71 13 10 26 10 / Hex: * 89 50 4e 47 0d 0a 1a 0a */ public static boolean isValidPNG(byte[] is) { try { byte[] b = Arrays.copyOfRange(is, 0, 8); if (Arrays.equals(b, PNG_HEADER)) { return true; } } catch (Exception e) { //Ignore return false; } return false; } /** * Check if the image is a JPEG. JPEG image files begin with FF D8 and end * with FF D9 */ public static boolean isValidJPEG(byte[] is) { try { // check first 2 bytes: byte[] b = Arrays.copyOfRange(is, 0, 2); if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd8) { return false; } // check last 2 bytes: b = Arrays.copyOfRange(is, is.length - 2, is.length); if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd9) { return false; } } catch (Exception e) { // Ignore return false; } return true; } /** Check if the image is a valid GIF. GIF files start with GIF and 87a or 89a. * http://www.onicos.com/staff/iz/formats/gif.html */ public static boolean isValidGIF(byte[] is) { try { byte[] b = Arrays.copyOfRange(is, 0, 6); //check 1st 3 bytes if(b[0]!='G' || b[1]!='I' || b[2]!='F') { return false; } if(b[3]!='8' || !(b[4]=='7' || b[4]=='9') || b[5]!='a') { return false; } } catch(Exception e) { // Ignore return false; } return true; } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } }