在 Java 中操作图像可以通过使用 Graphics 或 Graphics2D 上下文来实现。
可以使用ImageIO 类来加载JPEG 和PNG 等图像。 ImageIO.read 方法接受 File 来读取并返回 BufferedImage,它可用于通过其 Graphics2D(或 Graphics,它的超类)上下文来操作图像。
Graphics2D 上下文可用于执行许多图像绘制和操作任务。有关信息和示例,The Java Tutorials 的 Trail: 2D Graphics 将是一个非常好的开始。
以下是一个简化的示例(未经测试),它将打开一个 JPEG 文件,并绘制一些圆圈和线条(忽略例外):
// 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();
上面的代码将打开一个JPEG图像,并绘制一个椭圆和一条线。一旦执行了这些操作来操作图像,BufferedImage 就可以像处理任何其他Image 一样处理,因为它是Image 的子类。
例如,通过使用BufferedImage 创建ImageIcon,可以将图像嵌入JButton 或JLabel:
JLabel l = new JLabel("Label with image", new ImageIcon(img));
JButton b = new JButton("Button with image", new ImageIcon(img));
JLabel 和 JButton 都具有接受 ImageIcon 的构造函数,因此这是一种将图像添加到 Swing 组件的简单方法。