ImagePath with %20 is not working

213 Views Asked by At

I have the following code:

labelShowImagenApp.setIcon(new ImageIcon(rutaAbs.toURI().toURL()));

where rutaAbs is a path to an image file. The problem is that when that path contains spaces (like "im a png.png") it doesn't work, the label remains empty.

Hope someone can help me, thanks.

edit: I have noticed that if a folder that contains the image has spaces, it will not work either.

3

There are 3 best solutions below

0
On BEST ANSWER

I have fixed it doing this:

            if (rutaAbs.toString().contains("%20")){
                String replacedPath = (rutaAbs.toString().replace("%20", " "));
                rutaAbs = new File(replacedPath);
            }

Thanks a lot everyone for your answers.

3
On

Try this:

labelShowImagenApp.setIcon(new ImageIcon(URLDecoder.decode(rutaAbs.toURI().toURL(), "UTF-8")));

edited.

6
On

For a File use:

labelShowImagenApp.setIcon(new ImageIcon(rutaAbs.getPath()));

(For other readers.) For a resource in the application (possibly inside a jar) use

labelShowImagenApp.setIcon(new ImageIcon(getClass().getResource("/...")));

Corrected Answer:

This is how I in general do it:

BufferedImage img = ImageIO.read(rutaAbs);
ImageIcon icon = new ImageIcon(img);
icon.getImage().flush();  // @mKorbel
labelShowImagenApp.setIcon(icon);