La manipolazione delle immagini in Java può essere ottenuta utilizzando i contesti Graphics
o Graphics2D
.
È possibile caricare immagini come JPEG e PNG utilizzando la classe ImageIO
. Il metodo ImageIO.read
accetta un File
da leggere e restituisce un valore BufferedImage
, che può essere utilizzato per manipolare l'immagine tramite il relativo contesto Graphics2D
(o Graphics
, la sua superclasse).
Il contesto Graphics2D
può essere utilizzato per eseguire molte attività di disegno e manipolazione delle immagini. Per informazioni ed esempi, il Trail: 2D Graphics di The Java Tutorials sarebbe un ottimo inizio.
che segue è un esempio semplificato (non testata) che aprirà un file JPEG, e trarre alcune cerchi e linee (le eccezioni sono ignorati):
// Open a JPEG file, load into a BufferedImage.
BufferedImage img = ImageIO.read(new File("image.jpg"));
// Obtain the Graphics2D context associated with the BufferedImage.
Graphics2D g = img.createGraphics();
// Draw on the BufferedImage via the graphics context.
int x = 10;
int y = 10;
int width = 10;
int height = 10;
g.drawOval(x, y, width, height);
g.drawLine(0, 0, 50, 50);
// Clean up -- dispose the graphics context that was created.
g.dispose();
Il codice di cui sopra si aprirà un'immagine JPEG, e disegnare un ovale e una linea.Una volta eseguite queste operazioni per manipolare l'immagine, è possibile gestire BufferedImage
come qualsiasi altro Image
, in quanto è una sottoclasse di Image
.
Ad esempio, creando un ImageIcon
usando l'BufferedImage
, si può incorporare l'immagine in un JButton
o JLabel
:
JLabel l = new JLabel("Label with image", new ImageIcon(img));
JButton b = new JButton("Button with image", new ImageIcon(img));
Il JLabel
e JButton
entrambi hanno costruttori che prendono in ImageIcon
, in modo che possa essere un modo semplice per aggiungere un'immagine a un componente Swing.