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........
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.
Why don't you just take the substring after the last dot?
Alternatively use Apache Commons FileIO's class FilenameUtils
which provides a method to get the extension from a path.
Please note that you also might want to add that extension to your output file, it might get confusing if out.jpg
was actually a PNG file.
精彩评论