简体   繁体   English

使用java从url复制图像

[英]Copying an image from url using java

I am trying to download an image from URL. 我正在尝试从URL下载图像。 I use the Apache Commons library: 我使用Apache Commons库:

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

While opening the image it says not an PNG file. 打开图像时,它不是PNG文件。 Is this a good way to download images from url to local? 这是将图像从网址下载到本地的好方法吗?

Updated . 更新 。 Thankyou guys for your answers i undestand that i need to get the connection.getContentType(); 谢谢你们的回答我不知道我需要得到connection.getContentType(); and then save it as jpg or png as it is. 然后将其保存为jpg或png。

if you check the url, It is JPEG file. 如果你检查网址,它是JPEG文件。 Try to execute program after renaming file name to test.jpeg.. 将文件名重命名为test.jpeg后尝试执行程序。

Checking for the content type see this SO Question . 检查内容类型请参阅此SO问题 Then use this to save the file to the right type. 然后使用此选项将文件保存为正确的类型。

Running wget on this URL and looking at the HTTP response, looks like the file type is explicitly specified as JPEG: 在此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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM