Groovy download image from URL

14,009

Solution 1

Does this work? I believe it should:

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
    out << new URL(address).openStream()
  }
}

Solution 2

Thanks Tim, I also found your answer very helpful, just small note: Looks like you haven't closed URL stream. I'm just starting with Groovy, and I've heard that it close steams when exit from closure so we can change code like that:

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
      new URL(address).withInputStream { from ->  out << from; }
  }
}

Solution 3

You can get image type from their content type - URLConnection.getContentType() or from byte array:

content="http://www.google.ru/images/logo.png".toURL().getBytes()
ext=URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(content)).replaceFirst("^image/","")
new File("logo."+ext).setBytes(content)
Share:
14,009
StartingGroovy
Author by

StartingGroovy

Started with basic Java &amp; Groovy. Aiming to learn more about programming in general as well as C++.

Updated on June 13, 2022

Comments

  • StartingGroovy
    StartingGroovy about 2 years

    I am wondering what the proper way to go about downloading the image from this RUL would be: http://www.hidemyass.com/proxy-list/img/port/7018246/1

    The way I tried downloading it, leaves the file in an unknown format. Current code snippet I tested out is:

    public void download(def address) {
    
        def file = new FileOutputStream(address.tokenize("/")[-1])
        def out = new BufferedOutputStream(file)
        out << new URL(address).openStream()
        out.close()
    }