VICKY-TSC VICKY-TSC - 26 days ago 16
Java Question

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

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

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

Answer

When I first looked at this question I didn't think you could do it, the only time Java is concerned with the format of an image is when the Image is being loaded into memory from the file. After that, format is irrelevant. Here is a question that is similar to yours:

There are a couple of work arounds, You can determine the format of the Image before it gets loaded into memory. Heres an example that gets the ImageFormat from an ImageInputStream:

Or you could just do something more simple like this:

public String getFormat(String imageName)
{
    String temp = new String(imageName);
    temp.toLowerCase();

    if(temp.endsWith(".png"))
        return "PNG";

    if(temp.endsWith(".gif"))
        return "GIF";
}

Hope this info helped!


UPDATE:

You can also use a switch statement in Java 7:

public String getFormat(String imageName)
{
    switch(imageName.toLowerCase())
    {
        case ".png": return "PNG";
        case ".gif": return "GIF";
        case ".tiff": return "TIFF";
        case ".jpg": return "JPG";
        case ".jpeg": return "JPEG";
        case ".tiff": return "TIFF";
    }

    return "UNKNOWN";
}
Comments