Saturday, 20 August 2016

How to check whether image is exist in the URL or not using java?

This is to tell most of the time when we show images from the different server may not be available due to (HTTP 404 or HTTP 500). To tackle this issue we can have some default images when image is not available



public static boolean isImageExist(String urlName) throws IOException {
    URL url =new URL(urlName);
    try {
        Image image= ImageIO.read(url.openStream());
        return image != null;
    }
    catch ( FileNotFoundException e) {
        return false;
    }
}

To call this method 


try {
    if (isImageExist(imageUrl)){
        return imageUrl;
    }
} catch (IOException e) {
// Here you can display some no image url 
    return defaultImage;
}