Download picture from URL--java and Python implementation method comparison
Blog Category:
- A little bit of technical notes
Javapython Picture Download
First, the implementation of Java method
- First read the picture
Java code
- Method One: Directly read the picture according to the URL
- Private static BufferedImage read (String imageUrl) throws IOException {
- URL url = new URL (IMAGEURL);
- BufferedImage image = Imageio.read (URL);
- return image;
- }
Java code
- If you need to set some of the properties in connection, such as Requestproperty, then use mode two:
- Private static BufferedImage read (String imageUrl) throws IOException {
- URL url = new URL (IMAGEURL);
- HttpURLConnection conn = (httpurlconnection) url.openconnection ();
- //conn.setrequestproperty ("Referer", Referer);
- Conn.setrequestmethod ("GET");
- BufferedImage image = Imageio.read (Conn.getinputstream ());
- return image;
- }
2. Then save the picture
Java code
- Private static void Save (bufferedimage image, String destimageurl)
- throws IOException {
- File ImageFile = new File (Destimageurl);
- FileOutputStream OutStream = new FileOutputStream (ImageFile);
- Imageio.write (image, "jpg", outstream);
- Imageio.write (image, "gif", OutStream);
- Imageio.write (image, "png", OutStream);
- Imageio.write (image, "JPEG", outstream);
- }
3. How to get the type of picture (jpg, Jpeg, GIF, PNG, etc.)
Java code
- Public static String get (byte[] imagebt) throws IOException {
- String type = "";
- Memorycacheimageinputstream MCIS = null;
- try {
- MCIS = New Memorycacheimageinputstream (new Bytearrayinputstream (
- IMAGEBT));
- Iterator<imagereader> it = imageio.getimagereaders (MCIS);
- While (It.hasnext ()) {
- ImageReader reader = (imagereader) it.next ();
- return Reader.getformatname ();
- }
- } finally {
- if (MCIS! = null) {
- try {
- Mcis.close ();
- } catch (IOException IoE) {
- }
- }
- }
- return type;
- }
Ii. how Python is implemented
- One line of code for picture reading and saving
Python code
- From Urllib import Urlretrieve
- Urlretrieve (' http://img.chetx.com/chetxbbs/2005_04/09/1113039370066.gif ', ' e://mypicture.gif ')
2. One line of code to get the picture type
Python code
- Import IMGHDR
- Imghdr.what (' MyPicture.gif ')
Iii. Summary
Compared to the implementation of Java,python is really too concise and clear
Download picture from URL--java and Python implementation method comparison