在一些java需要上傳的需求中,大家都需要驗證上傳文件的類型,那么上傳圖片時, 大家肯定會驗證擴展名,但是如果用戶把一個別的文件的擴展名改成jpg或者gif這樣上傳就不好判斷了,所以大家可以用下面的方法進行判斷
public static boolean isImage(byte[] imageContent) {
if (imageContent == null || imageContent.length == 0) {
return false;
}
Image img = null;
InputStream is = null;
try {
is = new ByteArrayInputStream(imageContent);
img = ImageIO.read(is);
if (img == null || img.getWidth(null) <= 0
|| img.getHeight(null) <= 0) {
return false;
}
return true;
} catch (Exception e) {
return false;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
posted on 2010-09-26 10:41
青菜貓(孫宇) 閱讀(2970)
評論(2) 編輯 收藏 所屬分類:
java