3

これは幅と高さに対して-1を返すため、画像の幅と高さを取得する方法を知りたいだけです:

private void resizeImage(Image image){
    JLabel imageLabel = new JLabel();

    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    System.out.println("Width:" + imageWidth);
    System.out.println("Height:" + imageHeight);
}
4

4 に答える 4

4

次のようにする必要があります。

BufferedImage bimg = ImageIO.read(new File(filename));
int width          = bimg.getWidth();
int height         = bimg.getHeight(); 

この投稿が言うように

于 2013-08-13T14:53:28.563 に答える
3

With Apache Commons Imaging, you can get image width and height with better performance, without reading entire image to memory.

Sample code below is using Sanselan 0.97-incubator (Commons Imaging is still SNAPSHOT as I write this):

final ImageInfo imageInfo = Sanselan.getImageInfo(imageData);
int imgWidth = imageInfo.getWidth();
int imgHeight = imageInfo.getHeight();
于 2017-07-31T05:22:44.300 に答える
0
    public static BufferedImage resize(final Image image, final int width, final int height){
    assert image != null;
    final BufferedImage bi = new BufferedImage(width, height, image instanceof BufferedImage ? ((BufferedImage)image).getType() : BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g = bi.createGraphics();
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();
    return bi;
}

上記のコードは、画像のサイズを変更する 1 つの方法です。通常、画像の幅と高さを取得するには、次のようにします。

image.getWidth(null);
image.getHeight(null);

これはすべて、画像が null ではないという前提に基づいています。

于 2013-08-13T14:46:16.320 に答える
0

imageあなたのケースでこれが起こる正確な理由は不明です。実際に何が起こっているのかを正確に指定していません。

とにかく、答えはJavaDocにあります:

public abstract int getWidth(ImageObserver observer)

画像の幅を決定します。幅がまだ不明な場合、このメソッドは -1 を返し、指定された ImageObserver オブジェクトに後で通知されます。

問題の画像の幅と高さをすぐに決定することは明らかにできません。高さと幅を解決できるときにこのImageObserverメソッドが呼び出されるインスタンスを渡す必要があります。

于 2013-08-13T13:44:59.540 に答える