package cn.chnmuseum.party.common.util; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.InputStream; public class ImageUtil { /** * 判断文件是否为图片<br> * <br> * * @param pInput 文件名<br> * @param pImgeFlag 判断具体文件类型<br> * @return 检查后的结果<br> * @throws Exception */ public static boolean isPicture(String pInput) { // 获得文件后缀名 String tmpName = pInput.substring(pInput.lastIndexOf(".") + 1); // 声明图片后缀名数组 String imgeArray[][] = {{"bmp", "0"}, {"jpeg", "4"}, {"jpeg", "5"}, {"jpg", "6"}, {"png", "7"}}; // 遍历名称数组 for (int i = 0; i < imgeArray.length; i++) { // 判断单个类型文件的场合 if (imgeArray[i][0].equals(tmpName.toLowerCase())) { return true; } } return false; } /** * 判断文件是否为图片文件(GIF,PNG,JPG) * * @return */ public static boolean isImage(byte[] b) { int len = b.length; byte n1 = b[len - 2]; byte n2 = b[len - 1]; byte b0 = b[0]; byte b1 = b[1]; byte b2 = b[2]; byte b3 = b[3]; byte b6 = b[6]; byte b7 = b[7]; byte b8 = b[8]; byte b9 = b[9]; if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') { return true; } else if (b0 == -1 && b1 == -40 && n1 == -1 && n2 == -39) { return true; } else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') { return true; } else if (b6 == (byte) 'E' && b7 == (byte) 'x' && b8 == (byte) 'i' && b9 == (byte) 'f') { return true; } else if (b0 == (byte) 'B' && b1 == (byte) 'M') { return true; } else { return false; } } /** * 通过读取文件并获取其width及height的方式,来判断判断当前文件是否图片,这是一种非常简单的方式。 * * @param imageFile * @return */ public static boolean isImage(InputStream imageFile) { Image img; try { img = ImageIO.read(imageFile); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; } finally { img = null; } } /** * 通过读取文件并获取其width及height的方式,来判断判断当前文件是否图片,这是一种非常简单的方式。 * * @param imageFile * @return */ public static boolean isImage1(byte[] imageFile) { ImageIcon ii = new ImageIcon(imageFile); int iconHeight = ii.getIconHeight(); int iconWidth = ii.getIconWidth(); if (iconHeight <= 0 || iconWidth <= 0) { return false; } return true; } }