java 如何在java中获取图像文件(BufferedImage)的格式(例如:jpen,png,gif)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11425521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:04:09  来源:igfitidea点击:

How to get the format(ex:jpen,png,gif) of image file (BufferedImage) in java

javabufferedimagefile-extensionimage-formats

提问by VICKY-TSC

i want to get the buffered image format or type of image using java,

我想使用java获取缓冲图像格式或图像类型,

 InputStream stream = request.getResponseStream();   
 BufferedImage image=  ImageIO.read(stream);
 LOGGER.info(image);

回答by dgregory

Refer the javax.imageio.ImageIO.read()code

参考javax.imageio.ImageIO.read()代码

This code originally implemented in groovy but translated into java so It may have a syntax error.

这段代码最初是用 groovy 实现的,但翻译成 java 所以它可能有语法错误。

public String read(InputStream input) throws IOException {
    ImageInputStream stream = ImageIO.createImageInputStream(input);

    Iterator iter = ImageIO.getImageReaders(stream);
    if (!iter.hasNext()) {
        return null;
    }
    ImageReader reader = (ImageReader) iter.next();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(stream, true, true);
    BufferedImage bi;
    try {
        bi = reader.read(0, param);
        return reader.getFormatName();
    } finally {
        reader.dispose();
        stream.close();
    }
}

回答by Mahesh

This code might help you to get the extension of image

此代码可能会帮助您获得图像的扩展名

public static String getFormate(String ImageName) {

    return (ImageName.substring(ImageName.indexOf('.'),ImageName.length()));
}

In the above code first it searches dot(.) and with help of substring() it will return the extension

在上面的代码中,它首先搜索 dot(.) 并在 substring() 的帮助下返回扩展名