Groovy download image from URL

后端 未结 3 1450
感动是毒
感动是毒 2021-02-07 14:59

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 downl

相关标签:
3条回答
  • 2021-02-07 15:06

    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; }
      }
    }
    
    0 讨论(0)
  • 2021-02-07 15:15

    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)
    
    0 讨论(0)
  • 2021-02-07 15:18

    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()
      }
    }
    
    0 讨论(0)
提交回复
热议问题