用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组件。