Vinay
Vinay

Reputation: 111

How to know if the image exists or not by reading URL in Java?

http://nichehire.com/Nichehire/upload/[email protected]

I have a requirement to know whether an image exists or not by the given URL. For that I am using below code. In the below code I'm returning true if no error occurs and if the URL doesn't contain an image then false will returned. But the above given URL doesn't contain an image even though it returns true. Is something wrong in my code?

public static boolean exists(String URLName) {
    boolean result = false;
    try {
        InputStream input = (new URL(URLName)).openStream();
        result = true;
    } catch (IOException ex) {
        System.out.println("Image doesnot exits :");
    }   
    return result;
} 

Upvotes: 3

Views: 14004

Answers (4)

vikbehal
vikbehal

Reputation: 1524

try
    boolean isImage(String image_path){
    Image image = new ImageIcon(image_path).getImage();
    if(image.getWidth(null) == -1){
         return false;
    }
    else{
         return true;
    }
}

or

The Image Magick project has facilities to identify image and there's a Java wrapper for Image Magick called JMagick which I think you may want to consider instead of reinventing the wheel:

I'm using Image Magick all the time, including its "identify" feature from the command line and it never failed once to identify a picture. Back in the days where I absolutely needed that feature and JMagick didn't exist yet I used to Runtime.exec() ImageMagick's identify command from Java and it worked perfectly. Nowadays that JMagick exist this is probably not necessary anymore (but I haven't tried JMagick yet).

Note that it gives much more than just the format, for example:

$  identify tmp3.jpg 
tmp3.jpg JPEG 1680x1050 1680x1050+0+0 DirectClass 8-bit 293.582kb 

$  identify tmp.png
tmp.png PNG 1012x900 1012x900+0+0 DirectClass 8-bit 475.119kb 

Upvotes: 2

Flavio Troia
Flavio Troia

Reputation: 2809

[SOLVED] This source code works fine!

String url1 = "https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xft1/t39.1997-6/p200x200/851575_126362190881911_254357215_n.png";

Image image = ImageIO.read(new URL(url1));
if(image != null){
    System.out.println("IMAGE"); 
}else{
    System.out.println("NOT IMAGE"); 
}

Upvotes: 5

Andrew Thompson
Andrew Thompson

Reputation: 168825

..whether an image exists or not..

ImageIO.read(URL)

This is really the only way to ensure that:

  1. The URL points to something (not returning HTTP 404)
  2. The server allows access to the resource (e.g. not returning HTTP 500)
  3. The data at the end of the URL actually represents an image (as understood by Java) as opposed to being a text file renamed to some.gif.

Upvotes: 7

Badr Ghatasheh
Badr Ghatasheh

Reputation: 978

That's because you're assuming that any returned response is an image, although your URL could be returning anything, HTML, JSON .. anything.

Upvotes: 0

Related Questions