I do not understand the Image class! What am I doing wrong here?

pretty new here, but here is a little test code that explains my problem. The value printed is -1. I just don’t have the slightest idea on how to return the pixel width of my image, did I miss something very obvious here? This whole ImageObserver object does not make sense !!!

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;



    class imagetest2 extends JPanel {
        Image i =Toolkit.getDefaultToolkit().getImage(/*image*/);

        public int test(){
            int x = i.getWidth(null);
            return x;
        }


    }

    class imagetest {
        public static void main(String args[]){
            imagetest2 tesst = new imagetest2();
            System.out.print(tesst.test());
        }
    }
+3
source share
2 answers

Toolkit.getDefaultToolkit().getImage() can asynchronously load an image that will almost never be what you want.

Use ImageIOand a BufferedImage, as well getWidth(), and getHeight()no argument ImageObserver(though others will work if you pass null):

BufferedImage image = ImageIO.read("/*image*/");
int width = image.getWidth();
+5
source

. , , :

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;

class ImageTest 
{
    BufferedImage img;

    public static int getWidthFromImage(String filename)
    {
        BufferedImage image;
        int width;
        try
        {
            image = ImageIO.read(new File(filename));
            return image.getWidth();
        }
        catch(IOException e)
        {
            System.out.println("Something terrible happened! " + e.getMessage());
            e.printStackTrace();
        }
        return -1;
    }
    public static void main(String args[])
    {
        System.out.print("The width of the image in pixels is: " + getWidthFromImage(args[0]));
    }
}
0

All Articles