Bonjour,
Je tente de créer l'image (fichier jpg) d'un composant par la méthode :
Le problème, c'est que le répertoire "c:/REP/" n'existe pas. J'obtiens bien une IOException (FileNotFoundException). Mais mon problème est le suivant : Juste derrière, j'obtiens un NullPointerException :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 /** Crée l'image d'un composant. Source trouvée sur "http://java.developpez.com/faq/gui/?page=generalitesAWTSwing#GRAPHIQUE_AWT_enregistrer_image". */ private void créerImage(Component component) { BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); if(!component.isOpaque()){ Color bg = component.getBackground(); bg = (bg.getAlpha() < 255) ? new Color(bg.getRed(), bg.getGreen(), bg.getBlue()) : bg; Color color = g2d.getColor(); g2d.setColor(bg); g2d.fillRect(0, 0, component.getWidth(), component.getHeight()); g2d.setColor(color); } component.paint(g2d); g2d.dispose(); try { this.fichierImage = new File("c:/REP" + '/' + this.nomImage + ".jpg"); ImageIO.write(image, "jpeg", this.fichierImage); } catch (IOException e) { e.printStackTrace(); } }
En debug, je pense avoir trouvé la ligne provoquant l'exception :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3 Caused by: java.lang.NullPointerException at javax.imageio.ImageIO.write(Unknown Source) at plado.ressources.PMigEdition.créerImage(PMigEdition.java:203)
J'aimerais comprendre ce qu'il se passe, si ce NullPointerException est normal ? Où ai-je fait une faute ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 //Classe ImageIO : public static boolean write(RenderedImage im, String formatName, File output) throws IOException { if (output == null) { throw new IllegalArgumentException("output == null!"); } ImageOutputStream stream = null; try { output.delete(); stream = createImageOutputStream(output); } catch (IOException e) { throw new IIOException("Can't create output stream!", e); } boolean val; try { val = write(im, formatName, stream); } finally { stream.close(); // ICI } return val; }
Partager