Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-Write image from a URL

I am trying to download an image from an url...My code is :

String url = "http://mysite.com/image.xyz" 

where xyz can be jpg/png/jpeg..

now am able read the image from url using

BufferedImage image = ImageIO.read(url);

Now what i need is that while writing the image to a file using:

ImageIO.write(image, "variable" , new File("C:\\out1.jpg"));

i need the value of variable to be replaced by the value of xyz...where value of xyz will be extracted from url....

So how to achieve this........

like image 592
RanRag Avatar asked May 19 '26 14:05

RanRag


1 Answers

Use the class java.net.URL :

URL u = new URL(url);
String name = u.getFile();
String ext = name.substring(name.lastIndexOf(".") + 1);

In ext you have the extension.

[EDIT]

A few notes on other answers posted :

They are both good answers unless you happen to have an URL with query params (like http://www.example.org/folder/file.png?size=big ).

Using last three chars, it would return "big" instead of png.

Also, if the image is .jpeg it would return "peg".

Using simply after last "." in string is as well dangerous, more or less for the same reason of query params: it would return ".png?size=big".

java.net.URL will take into account all these situations, and return the file name only. For there, extracting the extension is still a matter of "finding the point", but at least on an already cleaned String.

like image 113
Simone Gianni Avatar answered May 22 '26 04:05

Simone Gianni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!