码迷,mamicode.com
首页 > 编程语言 > 详细

java读取远程url图片,得到宽高

时间:2016-01-06 15:27:34      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

链接地址:http://blog.sina.com.cn/s/blog_407a68fc0100nrb6.html

import java.io.IOException;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import javax.imageio.ImageIO;

public class Img2 {
//读取远程url图片,得到宽高
    public int[] returnImgWH(String imgurl) {
        boolean b=false;
        try {
            //实例化url
            URL url = new URL(imgurl);
            //载入图片到输入流
            java.io.BufferedInputStream bis = new BufferedInputStream(url.openStream());
            //实例化存储字节数组
            byte[] bytes = new byte[100];
            //设置写入路径以及图片名称
            OutputStream bos = new FileOutputStream(new File( "C:\\thetempimg.gif"));
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
            //关闭输出流
            b=true;
        } catch (Exception e) {
            //如果图片未找到
            b=false;
        }
        int[] a = new int[2];
        if(b){    //图片存在
            //得到文件
            java.io.File file = new java.io.File("C:\\thetempimg.gif");
            BufferedImage bi = null;
            try {
                //读取图片
                bi = javax.imageio.ImageIO.read(file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            a[0] = bi.getWidth(); //获得 宽度
            a[1] = bi.getHeight(); //获得 高度
            //删除文件
            file.delete();
        }else{     //图片不存在
            a=null;
        }
       return a;

    }

    public static void main(String[] args) {
        Img2 i = new Img2();
        int[] a=i.returnImgWH("http://www.baidu.com/img/baidu_logo.gif");
        if(a==null){
            System.out.println("图片未找到!");
        }else{
            System.out.println("宽为" + a[0]);
            System.out.println("高为" + a[1]);
        }
    }
}

java读取远程url图片,得到宽高

标签:

原文地址:http://www.cnblogs.com/wvqusrtg/p/5105387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!