Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download image from from url in java?

Tags:

java

url

I have been trying to download an image from url via java.
I tried to solve it with many ways but I didn't succeed.

I'm writing my ways hoping someone will find where it went wrong:

With the first and second ways I get the following error while I'm trying to open the image:

... file appears to be damaged, corrupted, or is too large

...and its size is smaller than it should be.

I guess it's related to encoding.

First way:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg");
InputStream in = url.openStream();
Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);
in.close();

Second way:

File f= new File("c:\\image.jpg");
URL myUrl = new URL("http://www.avajava.com/images/avajavalogo.jpg");
FileUtils.copyURLToFile(myUrl, f);

With way 3 i get Exception in thread "main" java.lang.IllegalArgumentException: image == null!

Third way:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

I really need your help!!! I have been trying to solve it a long time ago without success.

Thanks in advance!!!

like image 481
coral Avatar asked Dec 24 '22 01:12

coral


1 Answers

You have to specify the full location for the destination file in way 3:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("D:\\image\\downloaded.jpg");
ImageIO.write(img, "jpg", file);
like image 197
Vadivelan Avatar answered Jan 02 '23 22:01

Vadivelan