1. 程式人生 > >【JAVA】獲取本地和伺服器圖片的寬度和高度

【JAVA】獲取本地和伺服器圖片的寬度和高度

此篇文章轉自https://blog.csdn.net/u010648555/article/details/51647557

java獲取圖片的大小和尺寸,有兩種獲取的源,一種是讀取本地的圖片獲取大小和尺寸,一種是通過伺服器上圖片的地址獲取圖片的尺寸!下面整理出這兩種方式的簡易程式碼,希望幫助的大家和自己! 
我使用的Juint 進行的測試! 
1:獲取圖片的大小和尺寸

/**
      * 本地獲取
      * */
     @Test
     public void testImg2() throws IOException{
            File picture = new File("C:/Users/aflyun/Pictures/Camera Roll/1.jpg");
            BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture)); 
            System.out.println(String.format("%.1f",picture.length()/1024.0));// 源圖大小
            System.out.println(sourceImg.getWidth()); // 源圖寬度
            System.out.println(sourceImg.getHeight()); // 源圖高度

     }

2:獲取伺服器圖片的尺寸

/**
 * 獲取伺服器上的
 * @throws FileNotFoundException
 * @throws IOException
 */
public void getImg() throws FileNotFoundException, IOException{
    URL url = new URL("http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    BufferedImage image = ImageIO.read(connection.getInputStream());  
    int srcWidth = image .getWidth();      // 源圖寬度
    int srcHeight = image .getHeight();    // 源圖高度

    System.out.println("srcWidth = " + srcWidth);
    System.out.println("srcHeight = " + srcHeight);
}
/**
 * 獲取伺服器上的
 * 
 * @throws IOException
 */
public void testImg1() throws IOException{
    InputStream murl = new URL("http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid").openStream();
    BufferedImage sourceImg =ImageIO.read(murl);   
    System.out.println(sourceImg.getWidth());   // 源圖寬度
    System.out.println(sourceImg.getHeight());   // 源圖高度
}