Javaで画像を操作するには、Graphics
またはGraphics2D
のコンテキストを使用します。
ImageIO
クラスを使用すると、JPEGやPNGなどの画像を読み込むことができます。 メソッドは、を読み込み、Graphics2D
(またはGraphics
、スーパークラス)のコンテキストを使用してイメージを操作するために使用できるBufferedImage
を返します。
Graphics2D
コンテキストは、多くのイメージ描画操作タスクを実行するために使用できます。情報と例については、Trail: 2D GraphicsのThe Java Tutorialsが非常に良いスタートになります。続い
は(例外は無視される)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画像を開き、描画します楕円形と線。画像を操作するためにこれらの操作が実行されると、Image
のサブクラスであるので、BufferedImage
は他の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コンポーネントに画像を追加する簡単な方法です。