1. 程式人生 > >java 圖片資訊獲取

java 圖片資訊獲取

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()); // 源圖高度 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

 /**
      * 獲取伺服器上的
      * @throws FileNotFoundException
      * @throws
IOException */
@Test 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 */ @Test 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()); // 源圖高度 }