我熟悉 处理图像。我 从 URL 检索/读取图像,其中 URL 没有文件扩展名。然后我想 将图像写入/保存 到本地存储,但我必须指定图像文件扩展名(即 JPG、PNG 等),我无法通过 BufferedImage 检索它的扩展名。
请指出如何做到这一点?任何其他方法都可以。
原文由 Mr. 发布,翻译遵循 CC BY-SA 4.0 许可协议
我熟悉 处理图像。我 从 URL 检索/读取图像,其中 URL 没有文件扩展名。然后我想 将图像写入/保存 到本地存储,但我必须指定图像文件扩展名(即 JPG、PNG 等),我无法通过 BufferedImage 检索它的扩展名。
请指出如何做到这一点?任何其他方法都可以。
原文由 Mr. 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果对象是 URL,则使用 ImageIO.createImageInputStream(obj) 的建议将不起作用。
一种替代方法是使用 URLConnection.guessContentTypeFromStream(InputStream stream) 方法。此方法通过检查流的前 12 个字节来猜测内容类型。
使用此方法的一个复杂问题是它要求给定的流参数被标记支持,而 java url.openStream() 返回的流不受标记支持。
此外,如果您想确定内容类型并将图像下载到 BufferedImage,那么最好只下载一次内容(而不是进行两次传递,一次确定内容类型,第二次下载图像)。
一种解决方案是使用 PushbackInputStream。 PushbackInputStream 可用于下载第一个初始字节以确定内容类型。然后可以将字节推回到流上,以便 ImageIO.read(stream) 可以完整地读取流。
可能的解决方案:
// URLConnection.guessContentTypeFromStream only needs the first 12 bytes, but
// just to be safe from future java api enhancements, we'll use a larger number
int pushbackLimit = 100;
InputStream urlStream = url.openStream();
PushbackInputStream pushUrlStream = new PushbackInputStream(urlStream, pushbackLimit);
byte [] firstBytes = new byte[pushbackLimit];
// download the first initial bytes into a byte array, which we will later pass to
// URLConnection.guessContentTypeFromStream
pushUrlStream.read(firstBytes);
// push the bytes back onto the PushbackInputStream so that the stream can be read
// by ImageIO reader in its entirety
pushUrlStream.unread(firstBytes);
String imageType = null;
// Pass the initial bytes to URLConnection.guessContentTypeFromStream in the form of a
// ByteArrayInputStream, which is mark supported.
ByteArrayInputStream bais = new ByteArrayInputStream(firstBytes);
String mimeType = URLConnection.guessContentTypeFromStream(bais);
if (mimeType.startsWith("image/"))
imageType = mimeType.substring("image/".length());
// else handle failure here
// read in image
BufferedImage inputImage = ImageIO.read(pushUrlStream);
原文由 JohnC 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
使用 ImageReader.getFormatName()
您可以使用 ImageIO.getImageReaders(Object input) 获取文件的图像阅读器。
我自己没有测试过,但你可以试试这个: