直接贴代码
public static void main(String[] args) {
String picUrl = "http://placeimg.com/640/480/any.jpg";
ByteArrayOutputStream out = null;
InputStream inputStream = null, byteInput = null;
ImageInputStream iis = null;
try {
URL url = new URL(picUrl);
URLConnection connection = url.openConnection();
int buffSize = 4096;
out = new ByteArrayOutputStream(buffSize);
inputStream = connection.getInputStream();
byte[] temp = new byte[buffSize];
int size;
while ((size = inputStream.read(temp)) != -1) {
out.write(temp, 0, size);
}
byte[] content = out.toByteArray();
//重新转换成stream,转换成imageIO
byteInput = new ByteArrayInputStream(content);
BufferedImage image = ImageIO.read(byteInput);
System.out.println("图片宽:" + image.getWidth());
System.out.println("图片高:" + image.getHeight());
System.out.println("图片大小:" + content.length);
//根据图片后缀查看图片类型
System.out.println("图片类型:"+ picUrl.substring(picUrl.lastIndexOf(".") + 1, picUrl.length()));
//一下包含查看图片类型的方式
if (isGIF(content)) {
System.out.println("图片是GIF");
}
if (isJPEGHeader(content)) {
System.out.println("图片是JPEG");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
//关闭流失败
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//关闭流失败
}
}
if (byteInput != null) {
try {
byteInput.close();
} catch (IOException e) {
//关闭流失败
}
}
}
}
private static boolean isBMP(byte[] buf){
byte[] markBuf = "BM".getBytes(); //BMP图片文件的前两个字节
return compare(buf, markBuf);
}
private static boolean isICON(byte[] buf) {
byte[] markBuf = {0, 0, 1, 0, 1, 0, 32, 32};
return compare(buf, markBuf);
}
private static boolean isWEBP(byte[] buf) {
byte[] markBuf = "RIFF".getBytes(); //WebP图片识别符
return compare(buf, markBuf);
}
private static boolean isGIF(byte[] buf) {
byte[] markBuf = "GIF89a".getBytes(); //GIF识别符
if(compare(buf, markBuf))
{
return true;
}
markBuf = "GIF87a".getBytes(); //GIF识别符
if(compare(buf, markBuf))
{
return true;
}
return false;
}
private static boolean isPNG(byte[] buf) {
byte[] markBuf = {(byte) 0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A}; //PNG识别符
// new String(buf).indexOf("PNG")>0 //也可以使用这种方式
return compare(buf, markBuf);
}
private static boolean isJPEGHeader(byte[] buf) {
byte[] markBuf = {(byte) 0xff, (byte) 0xd8}; //JPEG开始符
return compare(buf, markBuf);
}
private static boolean isJPEGFooter(byte[] buf)//JPEG结束符
{
byte[] markBuf = {(byte) 0xff, (byte) 0xd9};
return compare(buf, markBuf);
}
private static boolean compare(byte[] buf, byte[] markBuf) {
for (int i = 0; i < markBuf.length; i++) {
byte b = markBuf[i];
byte a = buf[i];
if(a!=b){
return false;
}
}
return true;
}
稍微解释一下:
1、代码中识别图片的类型,使用了两种方法,一种是根据图片的后缀,另外一种是根据图片的内容。严格的方式是根据图片的内容,但是这样就无法区分jpg和jpeg。
2、代码中识别图片的大小是按照图片的字节数,单位是B。
3、代码中用到多个stream,因为接收完之后,需要再次将字节转换成inputstream,再次转换成bufferImage,没有找到直接将字节转换成bufferImage的方式,如果有哪位大神知道,希望能留言。