从 URL 读写图像
我正在尝试从网址下载图像
...我的代码是:
String url = "http://mysite.com/image.xyz"
其中xyz
可以是jpg/png/jpeg..
现在可以从网址读取图像 现在我需要
BufferedImage image = ImageIO.read(url);
的是,在将图像写入文件时使用:
ImageIO.write(image, "variable" , new File("C:\\out1.jpg"));
我需要将 variable
的值替换为 xyz
的值...其中的值xyz 将被提取
来自 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........
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用类 java.net.URL :
在 ext 中你有扩展名。
[编辑]
关于发布的其他答案的一些注释:
它们都是很好的答案,除非您碰巧有一个带有查询参数的 URL(例如 http://www.example.org/folder/file.png?size=big )。
使用最后三个字符,它将返回“big”而不是 png。
另外,如果图像是 .jpeg,它将返回“peg”。
仅在最后一个“.”之后使用in string 也很危险,或多或少与查询参数的原因相同:它将返回“.png?size=big”。
java.net.URL 将考虑所有这些情况,并仅返回文件名。在那里,提取扩展仍然是“找到点”的问题,但至少是在已经清理过的字符串上。
Use the class java.net.URL :
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.
为什么不直接取最后一个点后面的子字符串呢?
或者使用 Apache Commons FileIO 的 FilenameUtils 类,它提供了从路径获取扩展名的方法。
请注意,您可能还想将该扩展名添加到输出文件中,如果
out.jpg
实际上是一个 PNG 文件,可能会感到困惑。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.