Liam B
Liam B

Reputation: 65

ImageIO and URLs

Having some annoying issues with loading images into a BufferedImage (image in the example) with the use of ImageIO.read, due to there being spaces in the Image name;

image = ImageIO.read(new File(getClass().getResource("/Pictures/H ello.jpg").getPath()));

If I rename the url(?) "/Pictures/H ello.jpg" to "/Pictures/Hello.jpg" and the source image to Hello.jpg it works just fine.

I've tried replacing the spaces with %20 as found on other questions and also a replace char of ' ' to '+'. So what am I doing wrong? Would encoding solve my problem and how would I do that?

Thanks,

Upvotes: 3

Views: 942

Answers (3)

Pavel K.
Pavel K.

Reputation: 436

if you want this way, then you need to decode the url:

image = ImageIO.read(new File(URLDecoder.decode(getClass().getResource("/Pictures/H ello.jpg").getPath(), "UTF-8")));

but, if I need to work with resources, I'd use overloaded method ImageIO.read(URL) or ImageIO.read(InputStream) :

image = ImageIO.read(getClass().getResource("/Pictures/H ello.jpg"));
image = ImageIO.read(getClass().getResourceAsStream("/Pictures/H ello.jpg"));

see apidoc

Upvotes: 1

nullpotent
nullpotent

Reputation: 9260

java.net.URL path = getClass().getResource("/Pictures/H ello.jpg");
ImageIO.read(new File(path.toURI())); 

Does this work? I think it should. URL will decode space as %20 and File constructor should process it properly as an URI

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109532

The following possibly works.

image = ImageIO.read(getClass().getResourceAsStream("/Pictures/H ello.jpg"));

Upvotes: 2

Related Questions