VICKY-TSC VICKY-TSC - 6 months ago 58
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=;;


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);

        return "PNG";

        return "GIF";

Hope this info helped!


You can also use a switch statement in Java 7:

public String getFormat(String imageName)
        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";