Java获取远程图片的宽与高
Java获取远程图片的宽与高
1 import java.awt.image.BufferedImage;
2 import java.io.BufferedInputStream;
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.URL;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 import javax.imageio.ImageIO;
13
14 /**
15 * 读取远程URL图片的宽和高
16 * @author tovep
17 * @since 2012-3-17
18 * */
19 public class ObtainRemoteImageWidthAndHeight {
20
21 /**
22 * 获取远程图片的宽和高
23 * */
24 public Map<String,Integer> obtainRemoteImageWAH(String imageURL){
25 boolean isClose = false;
26 Map<String,Integer> result = new HashMap<String, Integer>();
27 try {
28 //实例化图片URL
29 URL url = new URL(imageURL);
30 //载入远程图片到输入流
31 InputStream bis = new BufferedInputStream(url.openStream());
32 //实例化存储字节数组
33 byte[] buffer = new byte[500];
34 //设置写入路径以及图片名称
35 OutputStream bos = new FileOutputStream(new File("D:\\Temp\\thetempimg.gif"));
36 int len;
37 while((len = bis.read(buffer)) > 0){
38 bos.write(buffer, 0, len);
39 }
40 bis.close();
41 bos.flush();
42 bos.close();
43 //关闭输出流
44 isClose = true;
45 } catch (Exception e) {
46 //如果图片没有找到
47 isClose = false;
48 }
49 if(isClose){
50 File file = new File("D:\\Temp\\thetempimg.gif");
51 BufferedImage bi = null;
52 try{
53 //读取图片
54 bi = ImageIO.read(file);
55 }catch(IOException ex){
56 ex.printStackTrace();
57 }
58 result.put("width", bi.getWidth());
59 result.put("height", bi.getHeight());
60 //删除临时图片
61 file.delete();
62 }
63
64 return result;
65 }
66
67 public static void main(String[] args) {
68 ObtainRemoteImageWidthAndHeight oriwh = new ObtainRemoteImageWidthAndHeight();
69 String imageURL = "http://www.baidu.com/img/baidu_logo.gif";
70 Map<String,Integer> result = oriwh.obtainRemoteImageWAH(imageURL);
71 if(result == null){
72 System.err.println("图片没有找到...");
73 }else {
74 System.out.println(result);
75 }
76 }
77 }