1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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;
}
}