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