Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: can't get Image size.

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default can't get Image size.

    I'm making an applet game and it would be nice to get the width and height of an image,
    but for some reason the function getWidth(ImageObserver) as well as getHeight(ImageObserver) always return -1 for me, I cant find out why, I'm sure the Images are loaded correctly (they can be drawn on the screen), do I have to pass a specific ImageObserver or is there some other mistake?


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    What ImageObserver are you trying to use?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    I've tried my applet class, wich I use for drawing the images, and null, but both return -1.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    Would you mind throwing together an SSCCE that demonstrates how you're trying to do this?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    this is the code (i think) that matters
    public class mainapplet {
            public static mainapplet home;
            mask testmask;
            public void init(){
                    home = this;
                    Graphics g = this.getGraphics();
                    testmask = new mask(Img[0],g);
            }
     
    }
    class mask {
    	boolean filled[][];
    	public mask(Image Img, Graphics g){
    		g.drawImage(Img,0,0,mainapplet.home);
    		int width = Img.getWidth(mainapplet.home);
    		int height = Img.getHeight(mainapplet.home);
    		System.out.println(width+","+height);
           }
    }
    Last edited by samanesh; March 8th, 2011 at 10:56 AM.

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    Sorry, but I don't really think that's enough. I wanted an SSCCE so I could see all of the major pieces- initializing the image, etc. Plus it's easier to help if I can just copy and paste your code into my IDE and run it. :p
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    OK, ill just copy and paste my entire code
    import java.awt.*; 
    import java.awt.event.*;
    import java.applet.*; 
    import java.net.*;
    import java.io.*;
     
     
     
    //the main class
    public class mainapplet extends Applet implements Runnable {
    	//vars
    	public static mainapplet home;
    	player you;
    	MediaTracker Mt;
    	Thread t = null;
    	URL Base;
    	int tdelay;
    	boolean[] keysdown = new boolean[200];
    	//object list
    	animation Sprite[] = new animation[1000];
    	enemy Enemy[] = new enemy[30];
    	weapon Weapon[] = new weapon[200];
    	bullet Bullet[] = new bullet[600];
    	Image Img[] = new Image[100];
    	String ImgName[] = new String[100];
    	int Imgcount, animcount, bulletcount, enemycount, weaponcount, maskcount;	
    	int width,height;
    	//Double buffering stuff
    	Graphics bgraph;
    	Dimension dim;
    	Image tempImg;
    	mask blub;
     
    	//initilization
    	public void init(){
    		//keys
    		for(int a=0;a<200;a++)
    		keysdown[a] = false;
    		//constants
    		tdelay = 1000/60;
    		home = this;
    		//counters
    		animcount = 0;
    		Imgcount = 0;
    		bulletcount = 0;
    		enemycount = 0;
    		weaponcount = 0;
    		maskcount = 0;
    		//stuff...
    		Mt = new MediaTracker(this);
    		Base = getDocumentBase();
    		getImgs("Images/");	
    		you = new player(250,150);
    		addEnemy(40,0,0);
    		//double buffer stuff
    		width = 800;
    		height = 600;
    		dim = getSize();
    		tempImg = createImage(dim.width,dim.height);
    		bgraph = tempImg.getGraphics();
    		//more stuff
    		Graphics g = this.getGraphics();
    		blub = new mask(Img[0],g);
     
    	}
    	//start
    	public void start(){
    		if(t == null){
    			t = new Thread(this);
    			t.start();
    		}
    	}
    	//loads png images from a directory
    	public void getImgs(String directory){
    		File dir = new File(directory);
    		String[] list = dir.list();
    		for(int a=0;a<list.length;a++){
    			if(list[a].substring(list[a].length()-4).toLowerCase().compareTo(".png") == 0){
    				Img[Imgcount] = getImage(Base,directory+list[a]);
    				ImgName[Imgcount] = list[a].substring(0,list[a].length()-4).toLowerCase();
    				System.out.println(Imgcount+" "+ImgName[Imgcount]);
    				Imgcount++;
    			}
    		}
    		System.out.println("");
    	}
    	//adds a new sprite
    	public animation addSprite(double x, double y, int delay, String[] names){
    		Sprite[animcount] = new animation(x,y,delay,names);
    		animcount++;
    		return Sprite[animcount-1];
    	}
    	//removes a sprite
    	public boolean removeSprite(animation gone){
    		for(int a=0;a<animcount;a++){
    			if(Sprite[a] == gone){
    				animcount--;
    				Sprite[a] = Sprite[animcount];
    				return true;
    			}
    		}
    		return false;
    	}
    	//adds a new enemy
    	public enemy addEnemy(double x, double y, int type){
    		Enemy[enemycount] = new enemy(x,y,type);
    		enemycount++;
    		return Enemy[enemycount-1];
    	}
    	//removes an enemy, and its stuff
    	public boolean removeEnemy(enemy gone){
    		for(int a=0;a<enemycount;a++){
    			if(Enemy[a] == gone){
    				removeSprite(Enemy[a].sprite);
    				for(int b=0;b<Enemy[a].arms.length;b++)
    				removeWeapon(Enemy[a].arms[b]);
    				enemycount--;
    				Enemy[a] = Enemy[enemycount];
    				return true;
    			}
    		}
    		return false;
    	}
    	//adds a new weapon
    	public weapon addWeapon(int x, int y,int ammotype, int firetype, int[] delaypattern,boolean repeat, enemy parent){
    		Weapon[weaponcount] = new weapon(x,y,ammotype,firetype,delaypattern,repeat,parent);
    		weaponcount++;
    		return Weapon[weaponcount-1];
    	}
    	//removes a weapon
    	public boolean removeWeapon(weapon gone){
    		for(int a=0;a<weaponcount;a++){
    			if(Weapon[a] == gone){
    				weaponcount--;
    				Weapon[a] = Weapon[weaponcount];
    				return true;
    			}
    		}
    		return false;		
    	}
    	//adds a bullet
    	public bullet addBullet(double x, double y, int xspeed, int yspeed,int type){
    		Bullet[bulletcount] = new bullet(x,y,xspeed,yspeed,type);
    		bulletcount++;
    		return Bullet[bulletcount-1];
    	}
    	//removes a bullet
    	public boolean removeBullet(bullet gone){
    		for(int a=0;a<bulletcount;a++){
    			if(Bullet[a] == gone){
    				removeSprite(Bullet[a].sprite);
    				bulletcount--;
    				Bullet[a] = Bullet[bulletcount];
    				return true;
    			}
    		}
    		return false;
    	}
    	//returns the Image number of an image name
    	public int getImgNumber(String name){
    		name = name.toLowerCase();
    		int a;
    		for(a=0;a<Imgcount;a++){
    			if(ImgName[a].compareTo(name) == 0)
    			return a;			
    		}
    		return -1;
    	}
     
    	//run
    	public void run(){
    		try{
    			while(true){
    				//invoke step action of every object
    				if(you != null)
    				you.action();
    				for(int a=0;a<enemycount;a++)
    				Enemy[a].action();	
    				for(int a=0;a<weaponcount;a++)
    				Weapon[a].action();	
    				for(int a=0;a<bulletcount;a++)
    				Bullet[a].action();
    				repaint();
    				t.sleep(tdelay);
    			}
    		}
    		catch(Exception e){
    			System.out.println("run fail, "+e);
    		}
    	}
     
    	//double buffer - update override
    	public void update(Graphics g){
    		paint(g);
    	}
    	//draw all animated objects
    	public void paint(Graphics g){
    		bgraph.clearRect(0,0,dim.width,dim.height);
    		for(int a=0;a<animcount;a++){
    			Sprite[a].draw(g);
    		}
    		int s = 10;
    		if(you != null)
    		you.paint();
    		g.drawImage(tempImg,0,0,this);
    	}
     
    	//key bindings
    	public boolean keyDown(Event e, int key){
    		if(key > 1000)
    		key -= 900;
    		keysdown[key] = true;	
    		return true;
    	}
    	public boolean keyUp(Event e, int key){
    		if(key > 1000)
    		key -= 900;
    		keysdown[key] = false;	
    		return true;
    	}
    }
     
    //player object
    class player {
    	animation sprite;
    	int x,y,armor,shield,hp, width,height;
    	public player(int a,int b){
    		x = a;
    		y = b;
    		String[] spr = {"player"};
    		sprite = mainapplet.home.addSprite(a,b,100,spr);
    		armor = 100;
    		shield = 300;
    		hp = armor+shield;
    	}
    	//running stuff, keyactions
    	public void action(){
    		sprite.x = x;
    		sprite.y = y;
    		if(mainapplet.home.keysdown[Event.UP-900]){
    			if(y > 100)
    			y -= 5;
    		}
    		if(mainapplet.home.keysdown[Event.DOWN-900]){
    			if(y < 590)
    			y += 5;
    		}
    		if(mainapplet.home.keysdown[Event.LEFT-900]){
    			if(x > 15)
    			x -= 5;
    		}
    		if(mainapplet.home.keysdown[Event.RIGHT-900]){
    			if(x < 785)
    			x += 5;
    		}
    		//check if a bullet is hitting
    		bullet b;
    		for(int a=0;a<mainapplet.home.bulletcount;a++){
    			b = mainapplet.home.Bullet[a];
     
    		}
    	}
    	//draw stuff like health bars
    	public void paint(){
    		mainapplet.home.bgraph.setColor(Color.black);
    		mainapplet.home.bgraph.fillRect(0,0,12,mainapplet.home.height);
    		mainapplet.home.bgraph.fillRect(mainapplet.home.width-12,0,12,mainapplet.home.height);
    		double shieldpart = mainapplet.home.height/shield;
    		int rheight = (int)shieldpart;
    		if(hp > armor){
    			for(int a=0;a<shield;a++){
    				Color c = new Color(0,(int)(132*a/shield)+64,(int)(192*a/shield)+64);
    				mainapplet.home.bgraph.setColor(c);
    				mainapplet.home.bgraph.fillRect(1,(int)(mainapplet.home.height-shieldpart*a),10,rheight);
    				if(hp-armor < a)
    				break;
    			}
    		}	
    		double armorpart = mainapplet.home.height/armor;
    		rheight = (int)armorpart;
    		for(int a=0;a<armor;a++){
    			Color c = new Color((int)(192*a/armor)+64,(132*a/armor)+16,0);
    			mainapplet.home.bgraph.setColor(c);
    			mainapplet.home.bgraph.fillRect(mainapplet.home.width-11,(int)(mainapplet.home.height-armorpart*a),10,rheight);			
    			if(a > hp)
    			break;
    		}
    	}
    }
     
     
    //animation object
    class animation {
    	double x,y;
    	int delay,currentdelay,cyclelength,currentimg;
    	int[] Imgs;
    	//constructor(x,y,delay,images)
    	public animation(double a,double b,int c,String[] z){
    		x = a;
    		y = b;
    		delay = c;
    		cyclelength = z.length;
    		currentdelay = 0;
    		currentimg = 0;
    		Imgs = new int[cyclelength];
    		for(int d=0;d<cyclelength;d++)
    		Imgs[d] = mainapplet.home.getImgNumber(z[d]);			
    	}
    	public void draw(Graphics g){
    		mainapplet.home.bgraph.drawImage(mainapplet.home.Img[Imgs[currentimg]],(int)x,(int)y,mainapplet.home);
    		currentdelay++;
    		if(currentdelay == delay){
    			currentdelay = 0;
    			currentimg++;
    		}
    		if(currentimg == cyclelength)
    		currentimg = 0;	
    	}
    }
    //enemy object
    class enemy {
    	int weight,hp,behaviour,type;
    	double maxspeed,xspeed,yspeed,x,y;
    	animation sprite;
    	weapon[] arms;
    	//constructor
    	public enemy(double a, double b, int c){
    		x = a;
    		y = b;
    		type = c;
    		switch(type){
    			//enemy 0: slow, weak, low firepower
    			case 0:
    				String[] imgs = {"enemy_01_01","enemy_01_02"};
    				sprite = mainapplet.home.addSprite(x,y,2,imgs);
    				xspeed = 0;
    				yspeed = 1.7;
    				arms = new weapon[1];
    				int[] delay = {20,60};
    				arms[0] = mainapplet.home.addWeapon(24,34,0,0,delay,true,this);		
    			break;
    		}
    	}
    	public void action(){
    		sprite.x = x;
    		sprite.y = y;
    		x += xspeed;
    		y += yspeed;
    		if(y > 500)
    		mainapplet.home.removeEnemy(this);
    	}
    	public void fire(int weapon){
     
    	}
    }
    //enemy weapon object
    class weapon {
    	int currentdelay, delaytime, firetype,ammotype,x,y; //x,y relative to its parent
    	int[] delaypattern;
    	boolean repeat;
    	enemy parent;
    	//constructor(x,y,ammotype,firetype,delaypattern,repeatpattern?,parent)
    	public weapon(int a, int b,int t,int e,int[] delay, boolean r, enemy p){
    		x = a;
    		y = b;
    		ammotype = t;
    		firetype = e;
    		delaypattern = new int[delay.length];
    		delaypattern = delay;
    		parent = p;
    		currentdelay = 0;
    		delaytime = delaypattern[0];
    		repeat = r;
    	}
    	//every turn actions
    	public void action(){
    		if(delaytime == 0){
    			fire(firetype);
    			currentdelay++;
    			if(currentdelay == delaypattern.length){
    				if(repeat){
    					delaytime = delaypattern[0];
    					currentdelay = 0;
    				}				
    			}		
    			else
    			delaytime = delaypattern[currentdelay];	
    		}
    		delaytime--;
    	}
    	public void fire(int type){
    		switch(type){
    			//fire a bullet straight ahead
    			case 0:
    				mainapplet.home.addBullet(parent.x+x,parent.y+y,0,6,ammotype);	
    			break;
    		}
    	}
    }
    //bullet object
    class bullet {
    	double x,y,xspeed,yspeed;
    	int power,type;
     
    	animation sprite;
    	//constructor(x,y,xspeed,yspeed,type)
    	public bullet(double a,double b,double c,double d,int e){
    		x = a;
    		y = b;
    		xspeed = c;
    		yspeed = d;
    		type = e;
    		switch(type){
    			//standard bullet
    			case 0:
    				String[] imgs = {"bullet_01_01","bullet_01_02"};
    				sprite = mainapplet.home.addSprite(x,y,2,imgs);
    				power = 4;
    			break;
    		}
    	}
    	//running stuff
    	public void action(){
    		x += xspeed;
    		y += yspeed;
    		sprite.x = x;
    		sprite.y = y;
    		if(y > 600)
    		mainapplet.home.removeBullet(this);
    	}
     
     
    }
     
    //image mask
    class mask {
    	boolean filled[][];
    	public mask(Image Img, Graphics g){
    		g.drawImage(Img,0,0,mainapplet.home);
    		int width = Img.getWidth(mainapplet.home);
    		int height = Img.getHeight(mainapplet.home);
    		System.out.println(width+","+height);
    		/*g.clearRect(0,0,width,height);
    		Robot r = null;
    		boolean done = false;
    		try{
    			r = new Robot();			
    		}
    		catch(Exception e){}
    		Color c = r.getPixelColor(0,0);
    		Color d;
    		g.drawImage(Img,0,0,mainapplet.home);
    		filled = new boolean[width][height];
    		for(int a=0;a<width;a++){
    			for(int b=0;b<height;b++){
    				filled[a][b] = true;
    				d = r.getPixelColor(a,b);
    				if(d == c)
    				filled[a][b] = false;				
    			}
    		}*/
    	}
    }

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    Quote Originally Posted by samanesh View Post
    OK, ill just copy and paste my entire code
    Ack! No, please don't do that either. I'm sorry, I'm not trying to be obnoxious, but it's really important that we see the actual code you're running- without having to wade through so much extra stuff. We have hundreds of posts to get to, so we usually don't have time to look through your entire program. That's why we ask for an SSCCE. Click the link I posted above if you have questions on what should go into one.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    right, sorry.
    you will need a folder "Images" with 1 png Image in it for it to run.

    import java.awt.*; 
    import java.applet.*; 
    import java.net.*;
    import java.io.*;
     
    //the main class
    public class mapplet extends Applet implements Runnable {
    	//vars
    	public static mapplet home;
    	Image Img[] = new Image[100];
    	String ImgName[] = new String[100];
    	int Imgcount;	
    	URL Base;
    	mask testmask;
     
    	//initilization
    	public void init(){
    		Imgcount = 0;
    		Base = getDocumentBase();
    		getImgs("Images/");	
    		Graphics g = this.getGraphics();
    		testmask = new mask(Img[0],g);		
    	}
     
    	//loads png images from a directory
    	public void getImgs(String directory){
    		File dir = new File(directory);
    		String[] list = dir.list();
    		for(int a=0;a<list.length;a++){
    			if(list[a].substring(list[a].length()-4).toLowerCase().compareTo(".png") == 0){
    				Img[Imgcount] = getImage(Base,directory+list[a]);
    				Imgcount++;
    			}
    		}
    	}
    	public void run(){}
    }
     
    class mask {
    	public mask(Image Img, Graphics g){
    		g.drawImage(Img,0,0,mapplet.home);
    		int width = Img.getWidth(mapplet.home);
    		int height = Img.getHeight(mapplet.home);
    		System.out.println(width+","+height);
    	}
    }

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    There are a few things that stick out to me, but the most glaring is how you're trying to do your painting. If you're calling getGraphics() on anything other than an Image, you're doing something very wrong.

    Also, if I was being nitpicky, an SSCCE should only have been a couple lines long- reading in a specific image, possibly painting it, and printing out its width and height. It's going to take me a few minutes to wade through what you posted, even though it is much more boiled down than all of your code.
    Last edited by KevinWorkman; March 8th, 2011 at 11:39 AM.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #11
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    yes, i was still expirimenting with how to get Graphics to paint outside the paint method. This is my first java programming, so it sure has some things that can be improved. About the size: these functions are the functions i think can not be left out.

  12. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: can't get Image size.

    Okay, so your basic problem is that your image isn't done being loaded when you're calling the getWidth() and getHeight() functions. The API for Image actually explains that.

    There are two ways around this that pop out at me: Either use a MediaTracker (again, the API is your friend) to figure out when the image is done being loaded before trying to retrieve the width and height, or an ImageIcon instead.

    That's one of your problems. But I strongly suggest you also fix your painting code. Also, is there a reason you're using Applet and not JApplet?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. The Following User Says Thank You to KevinWorkman For This Useful Post:

    samanesh (March 8th, 2011)

  14. #13
    Junior Member
    Join Date
    Mar 2011
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: can't get Image size.

    thank you, this fixed my problem.
    the reason i use Applet is that I've never before heard of JApplet... ill check it out.

Similar Threads

  1. Replies: 2
    Last Post: February 14th, 2011, 05:36 PM
  2. Limit File Size or Request Size
    By tarek.mostafa in forum Java Servlet
    Replies: 3
    Last Post: June 12th, 2010, 04:28 PM
  3. Limit File Size or Request Size
    By tarek.mostafa in forum JavaServer Pages: JSP & JSTL
    Replies: 3
    Last Post: June 11th, 2010, 07:21 AM
  4. Pixel Alteration in an image/image rotation
    By bguy in forum Java Theory & Questions
    Replies: 3
    Last Post: November 1st, 2009, 10:50 AM
  5. [SOLVED] Change the size of an image
    By subhvi in forum Algorithms & Recursion
    Replies: 4
    Last Post: August 23rd, 2009, 11:44 PM