如何从中获得图像格式 URL 在 Java?

我有一个我得到的形象 url, 没有扩张/jpg,gif, png 等等。/.

下载图像没有问题。


BufferedImage image = null;
URL url = new URL/link/;
image = ImageIO.read/url/;


但是,我想知道将其保存到磁盘之前的文件扩展名。 我尝试了以下,

ImageIO.createImageInputStream/image/;


总是回报 null.


ImageInputStream iis = ImageIO.createImageInputStream/image/;
//where image is BufferImage but it is always returning null.

while /imageReaders.hasNext/// {
ImageReader reader = imageReaders.next//;
System.out.printf/"formatName: %s%n", reader.getFormatName///;

return ImageFormatTypes.valueOf/reader.getFormatName///;
}


任何建议将被认真考虑。
已邀请:

窦买办

赞同来自:

一旦你创造了 java.awt.Image, 格式将消失。 不是 PNG, 不是 JPEG, 这只是一个图像 Java. 因此,您无法从图像对象中获取图像格式。

你需要得到它 URL. 检查内容类型最可靠的方法 URL, 然后从供应商那里获得分机 ImageIO:


URL url = new URL/link/;
URLConnection conn = url.openConnection//;
String contentType = conn.getContentType//;

String suffix = null;
Iterator<imagereader> readers =
ImageIO.getImageReadersByMIMEType/contentType/;
while /suffix == null &amp;&amp; readers.hasNext/// {
ImageReaderSpi provider = readers.next//.getOriginatingProvider//;
if /provider != null/ {
String[] suffixes = provider.getFileSuffixes//;
if /suffixes != null/ {
suffix = suffixes[0];
}
}
}


你也可以保存 URL 在临时文件中使用 Files.probeContentType:


URL url = new URL/link/;
Path imageFile = Files.createTempFile/"image", null/;
try /InputStream stream = url.openStream/// {
Files.copy/stream, imageFile, StandardCopyOption.REPLACE_EXISTING/;
}

image = ImageIO.read/imageFile.toFile///;
String contentType = Files.probeContentType/imageFile/;
Files.delete/imageFile/;


但你仍然需要供应商 ImageIO, 从类型中获取扩展 MIME.
</imagereader>

冰洋

赞同来自:

在 Java 7+ 现在你可以使用
http://docs.oracle.com/javase/ ... %2529
.


----------
public static String probeContentType/Path path/
throws IOException


检查文件内容的类型。

此方法使用已建立的实现 FileTypeDetector 为了
检查此文件以确定其内容类型。 probeContentType 每一个
依次调用文件类型检测器来验证
文件类型。 如果识别文件,则返回内容类型。 如果一个
任何已安装的文件类型检测器都无法识别该文件。
, 要确定内容类型,请调用默认系统检测器
.

此虚拟机调用 Java 支持公共系统
文件类型检测器列表。 文件类型探测器安装
使用定义的服务提供商加载工具
班级 ServiceLoader. 文件类型探测器使用
系统引导程序。 如果找不到系统类引导加载程序
, 然后使用扩展类加载器; 如果扩展类装载机
找不到引导类引导。 文件类型
通常通过将它们放入文件中安装探测器。 JAR 经过
方法到应用程序类或扩展目录,文件
JAR 包含命名的提供程序配置文件
java.nio.file.spi.FileTypeDetector 在资源目录中
META-INF/services, 并且文件列出了一个或多个完整
具体子类的名称 FileTypeDetector, 谁有
零参数设计师。 如果搜索过程或实例
已安装的文件类型的文件探测器失败,它是无限期的
错误。 已安装的供应商的顺序
取决于具体实施。

此方法的返回值是类型类型的字符串形式
内容 Multipurpose Internet Mail Extension /MIME/, 定义
RFC 2045: 多用途互联网邮件扩展 /MIME/ 第一部分:
格式体互联网消息。 该字符串保证是
不同意 grammar 在 RFC.

要回复问题请先登录注册