從url下載圖片--java與python實現方式比較


一、java的實現方式

  1. 首先讀取圖片
Java代碼   收藏代碼
  1. //方式一:直接根據url讀取圖片  
  2. private static BufferedImage read(String imageUrl) throws IOException {  
  3.         URL url = new URL(imageUrl);  
  4.         BufferedImage image = ImageIO.read(url);  
  5.         return image;  
  6.     }  
Java代碼   收藏代碼
  1. //如果需要設置connection里的一些屬性,譬如RequestProperty,則采用方式二:  
  2. private static BufferedImage read(String imageUrl) throws IOException {  
  3.         URL url = new URL(imageUrl);  
  4.   
  5.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  6.         //conn.setRequestProperty("Referer", referer);  
  7.         conn.setRequestMethod("GET");  
  8.         BufferedImage image = ImageIO.read(conn.getInputStream());  
  9.         return image;  
  10.   
  11. }  

 

   2. 然后保存圖片

Java代碼   收藏代碼
  1. private static void save(BufferedImage image, String destImageUrl)  
  2.             throws IOException {  
  3.         File imageFile = new File(destImageUrl);  
  4.         FileOutputStream outStream = new FileOutputStream(imageFile);  
  5.   
  6.         ImageIO.write(image, "jpg", outStream);  
  7. ImageIO.write(image, "gif", outStream);  
  8. ImageIO.write(image, "png", outStream);  
  9. ImageIO.write(image, "jpeg", outStream);  
  10. }  

  3. 如何獲取圖片的類型(jpg、Jpeg、gif、png等)

Java代碼   收藏代碼
  1. public static String get(byte[] imageBT) throws IOException {  
  2.         String type = "";  
  3.         MemoryCacheImageInputStream mcis = null;  
  4.         try {  
  5.             mcis = new MemoryCacheImageInputStream(new ByteArrayInputStream(  
  6.                     imageBT));  
  7.             Iterator<ImageReader> it = ImageIO.getImageReaders(mcis);  
  8.             while (it.hasNext()) {  
  9.                 ImageReader reader = (ImageReader) it.next();  
  10.                 return reader.getFormatName();  
  11.             }  
  12.         } finally {  
  13.             if (mcis != null) {  
  14.                 try {  
  15.                     mcis.close();  
  16.                 } catch (IOException ioe) {  
  17.                 }  
  18.             }  
  19.         }  
  20.         return type;  
  21.     }  

 

 

二、python如何實現

  1. 一行代碼搞定圖片讀取和保存
Python代碼   收藏代碼
  1. from urllib import urlretrieve  
  2. urlretrieve(‘http://img.chetx.com/chetxbbs/2005_04/09/1113039370066.gif’, ‘e://mypicture.gif’)  

 

    2. 一行代碼搞定圖片類型獲取

Python代碼   收藏代碼
  1. import imghdr  
  2. imghdr.what(‘mypicture.gif')  

 

三、總結

    相比於Java,python的實現真的是太簡潔明了了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM