- Home ›
- Swing ›
- ImageIconクラス ›
- HERE
画像のサイズを取得する
ImageIconクラスのオブジェクトに読み込んだ画像ファイルのサイズを取得する方法を確認します。ImageIconクラスで用意されている「getIconHeight」メソッドと「getIconWidth」メソッドを使います。
まずは画像ファイルの高さを取得する「getIconHeight」メソッドです。
getIconHeight public int getIconHeight()
アイコンの高さを取得します。 戻り値: このアイコンのピクセル単位の高さ
ImageIconクラスのオブジェクトに読み込んだ画像の高さを返します。単位はピクセルですint型の値として取得できます。
次に画像ファイルの幅を取得する「getIconWidth」メソッドです。
getIconWidth public int getIconWidth()
アイコンの幅を取得します。 戻り値: このアイコンのピクセル単位の幅
ImageIconクラスのオブジェクトに読み込んだ画像の幅を返します。単位はピクセルですint型の値として取得できます。
この2つのメソッドを使うことで画像の高さと幅を取得する事が出来ます。
実際には次のように使用します。
ImageIcon icon = new ImageIcon("./img/sample.png"); int iconHeight = icon.getIconHeight(); int iconWidth = icon.getIconWidth();
サンプルプログラム
では実際に試してみましょう。今回はJLabelクラスのオブジェクトを作成する場合にImageIconクラスのオブジェクトを使ってラベルに画像を表示させた後で画像のサイズを取得してラベルに表示させてみます。
import javax.swing.*; import java.awt.BorderLayout; public class JImageIconTest2 extends JFrame{ public static void main(String[] args){ JImageIconTest2 frame = new JImageIconTest2(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10, 150, 150); frame.setTitle("タイトル"); frame.setVisible(true); } JImageIconTest2(){ ImageIcon icon = new ImageIcon("./hasami.png"); int iconHeight = icon.getIconHeight(); int iconWidth = icon.getIconWidth(); JLabel label = new JLabel(icon); label.setText(iconWidth + "×" + iconHeight); JPanel p = new JPanel(); p.add(label); getContentPane().add(p, BorderLayout.CENTER); } }
上記をコンパイルした後で実行すると次のように表示されます。
( Written by Tatsuo Ikura )