2012-06-27 45 views
3

我正在尝试从URL下载图像。我用的是Apache的百科全书库:使用java从url复制图像

org.apache.commons.io.FileUtils 
       .copyURLToFile(
         new URL(
           "https://lh3.ggpht.com/AXYMUV5cpne2vE9U3X8x87HgrbwijwiG50_yOnehU2MUPKDoJky-BKFOPZzZ07Pug8U=h230"), 
         new File("test.png")); 

当您打开它说不是一个PNG文件的图像。这是一个从url下载图像到本地的好方法吗?

已更新。 Thankyou球员为您的答案我undestand,我需要得到connection.getContentType();,然后保存为JPG或PNG,因为它是。

+2

这可能是因为你正在下载的图像是JPEG – tsukimi

+0

重命名下载的图像到test.jpg然后尝试打开它。 –

+0

如何查找它是否为JPG或PNG – Ramesh

回答

2

如果您检查网址,它是JPEG文件。尝试在将文件名重命名为test.jpeg后执行程序。

2

检查内容类型,请参阅SO Question。 然后用这个将文件保存到正确的类型。

0

运行在此URL wget和查看HTTP响应,看起来像文件类型是明确指定为JPEG:

 
--2012-06-27 16:55:30-- https://lh3.ggpht.com/AXYMUV5cpne2vE9U3X8x87HgrbwijwiG50_yOnehU2MUPKDoJky-BKFOPZzZ07Pug8U=h230 
Resolving lh3.ggpht.com... 74.125.237.108, 74.125.237.106, 74.125.237.107, ... 
Connecting to lh3.ggpht.com|74.125.237.108|:443... connected. 
HTTP request sent, awaiting response... 
    HTTP/1.0 200 OK 
    Access-Control-Allow-Origin: * 
    ETag: "v1" 
    Expires: Thu, 28 Jun 2012 06:50:40 GMT 
    Content-Disposition: inline;filename="unnamed.jpg" 
    Content-Type: image/jpeg 
    X-Content-Type-Options: nosniff 
    Date: Wed, 27 Jun 2012 06:50:40 GMT 
    Server: fife 
    Content-Length: 46597 
    X-XSS-Protection: 1; mode=block 
    Cache-Control: public, max-age=86400, no-transform 
    Age: 290 
    Connection: Keep-Alive 
Length: 46597 (46K) [image/jpeg]