从 URL 读写图像

发布于 2024-12-03 02:12:25 字数 483 浏览 5 评论 0原文

我正在尝试从网址下载图像...我的代码是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

茶底世界 2024-12-10 02:12:25

使用类 java.net.URL :

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

在 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 :

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.

惜醉颜 2024-12-10 02:12:25

为什么不直接取最后一个点后面的子字符串呢?

或者使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文