package net.sf.jasperreports.engine.util;

public class JRTypeSniffer {
  public static boolean isGIF(byte[] data) {
    if (data.length < 3)
      return false; 
    byte[] first = new byte[3];
    System.arraycopy(data, 0, first, 0, 3);
    if ((new String(first)).equalsIgnoreCase("GIF"))
      return true; 
    return false;
  }
  
  public static boolean isJPEG(byte[] data) {
    if (data.length < 2)
      return false; 
    if (data[0] == -1 && data[1] == -40)
      return true; 
    return false;
  }
  
  public static boolean isPNG(byte[] data) {
    if (data.length < 8)
      return false; 
    if (data[0] == -119 && data[1] == 80 && data[2] == 78 && data[3] == 71 && data[4] == 13 && data[5] == 10 && data[6] == 26 && data[7] == 10)
      return true; 
    return false;
  }
  
  public static boolean isTIFF(byte[] data) {
    if (data.length < 2)
      return false; 
    if ((data[0] == 73 && data[1] == 73) || (data[0] == 77 && data[1] == 77))
      return true; 
    return false;
  }
  
  public static byte getImageType(byte[] data) {
    if (isGIF(data))
      return 1; 
    if (isJPEG(data))
      return 2; 
    if (isPNG(data))
      return 3; 
    if (isTIFF(data))
      return 4; 
    return 0;
  }
  
  public static String getImageMimeType(byte imageType) {
    String mimeType = null;
    switch (imageType) {
      case 1:
        mimeType = "image/gif";
        break;
      case 2:
        mimeType = "image/jpeg";
        break;
      case 3:
        mimeType = "image/png";
        break;
      case 4:
        mimeType = "image/tiff";
        break;
    } 
    return mimeType;
  }
}
