Java 验证图片格式gif,jpeg,png,bmp

import java.io.ByteArrayInputStream;      
import javax.imageio.ImageIO;      
import javax.imageio.ImageReader;      
import javax.imageio.stream.MemoryCacheImageStream;      
public class ImageHelper      
{      
 public static boolean validateImageType(byte[] mapObj)      
 {      
  boolean ret =false;      
  ByteArrayInputStream bais = null;      
  MemoryCacheImageInputStream mcis = null;      
  try     
  {      
    bais = new ByteArrayInputStream(mapObj);      
    mcis = new MemoryCacheImageInputStream(bais);      
    Iteratoe<ImagerReader> itr = ImageIO.getImagerReaders(mcis);      
    while(itr.hasNext())      
    {      
      ImageReader reader = (ImagerReader)itr.next();      
      String imageName = reader.getClass().getSimpleName();      
      if(imageName!=null &&("GIFImageReader".equals(imageName)      
      ||"JPEGImageReader".equals(imageName)      
      ||"PNGImageReader".equals(imageName)      
      ||"BMPImageReader".equals(imageName)))      
      {      
        ret =true;      
      }      
    }      
  }      
  finally     
  {      
    //关闭流      
  }      
 }      
 public static boolean validateImageType(InputStream input)      
 {      
  return validateImageType(IOUtils.toByteArray(input));      
 }      
}

你可能感兴趣的:(java)