how to check for valid image


D

damon

hi,
I have a couple of files from which I want to create BufferedImage so
that I can display it on a jpanel.Problem is that their extensions are
unreliable.
/myimgs/image1.png

/myimgs/realimage2.txt

/myimgs/fakeimage3.png

the first two are actual png images and the last one is a text file
renamed as .png
Is there some way to test for the valid images?

I tried this

public boolean checkIfImageFile(String filename){
boolean isimage=false;
try{
BufferedImage bi=ImageIO.read(new File(filename));
if (bi!=null)isimage=true;
}catch(Exception e){
isimage=false;
}

return isimage;
}

Is this the way to do such a test?If there is a proper way please tell
me.
thanks in advance
sajan
 
Ad

Advertisements

M

markspace

the first two are actual png images and the last one is a text file
renamed as .png
Is there some way to test for the valid images?


What you have probably works well enough. I would open the file and
look for magic numbers and such, first, as it might be faster/less CPU.
As long as what you have seems to actually function, I don't see a
reason to change it.
 
A

Arne Vajhøj

I have a couple of files from which I want to create BufferedImage so
that I can display it on a jpanel.Problem is that their extensions are
unreliable.
/myimgs/image1.png

/myimgs/realimage2.txt

/myimgs/fakeimage3.png

the first two are actual png images and the last one is a text file
renamed as .png
Is there some way to test for the valid images?

I tried this

public boolean checkIfImageFile(String filename){
boolean isimage=false;
try{
BufferedImage bi=ImageIO.read(new File(filename));
if (bi!=null)isimage=true;
}catch(Exception e){
isimage=false;
}

return isimage;
}

Is this the way to do such a test?If there is a proper way please tell
me.

The technique looks fine.

I may have written the code slightly different, but it does not matter.

Arne
 
Ad

Advertisements

R

Roedy Green

the first two are actual png images and the last one is a text file
renamed as .png
Is there some way to test for the valid images?

Have a look at the code in the ImageInfo class part of the Common11
package you can download at
http://mindprod.com/products1.html#COMMON11
--
Roedy Green Canadian Mind Products
http://mindprod.com

Microsoft has a new version out, Windows XP, which according to everybody is the "most reliable Windows ever." To me, this is like saying that asparagus is "the most articulate vegetable ever."
~ Dave Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top