Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default cropping imageicon

    Is there a way to cut imageicon into pieces?? I have a spritesheet and i want to create pixelperfectcollision, but cannot find a way to check the collision on that single frame. how can i cut a piece from spritesheet and save it as a individual imaceicon?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: cropping imageicon

    Load a BufferedImage using ImageIO#read(...) and construct the ImageIcons with an argument obtained from BufferedImage#getSubimage(...).

    how can i cut a piece from spritesheet and save it as a individual imaceicon?
    Normally you wouldn't want to save an ImageIcon. Did you want to construct an ImageIcon or save an image to disk?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    I want to construct an ImageIcon so that i can use it in pixelperfect collision code. if i use buffered image will this code still work?

    Java Code:
    void drawSprite(Image source, Graphics2D g2d, int x, int y,
                         int columns, int frame, int width, int height){
    					
    		int frameX = (frame % columns) * width;
    		int frameY = (frame / columns) * height;
    		g2d.drawImage(source, x, y, x+width, y+height, frameX, frameY, frameX+width, frameY+height, this);
    	}
    And is it as fast as imageicon or is it slower or faster?

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: cropping imageicon

    I've used BufferedImages quite a bit and they display prettyfast. However, based on your drawSprite parameters I don't believe you want to add x to the width and y to the height. The width and height should remain the same regardless of where you place the image.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    I tryed whidout addind the X and y to width and height, well, the result was confusing ang ugly. sprites didnt work properly then.

  6. #6
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: cropping imageicon

    Are width and height that of the frame or of the image?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    Image. How to i use buffered image?? up to this point i have built my game over imageicon, but it seem that if i want to progress futher i need to use bufferedimage.

  8. #8
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    whyle using buffered image i keep getting this error C:\Users\Marko\Desktop\java>java boss.RType
    Exception in thread "main" java.lang.NullPointerException
    at boss.Boss.<init>(Boss.java:40)
    at boss.Board.<init>(Board.java:50)
    at boss.RType.<init>(RType.java:8)
    at boss.RType.main(RType.java:20)

  9. #9
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: cropping imageicon

    If you are using third party code which expects ImageIcon, then you are pretty much stuck with that. I can't help you since I don't know what the above classes look like. However, ImagIcon makes use of an instance of Image in its class. And BufferedImage is a subclass of Image. So the two image instances should be compatible.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    Java Code:
    package boss;
    
    import java.awt.Image;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    
    import java.util.ArrayList;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    
    public class Board extends JPanel implements Runnable {
    
    	private Boss boss;
    	private Image image;
        private Timer timer;
    	private Craft craft;
    
        private boolean ingame;
        private int B_WIDTH;
        private int B_HEIGHT;
    	private Thread animator;
    	private int Boss = 1;
    	
    	private final int DELAY = 10;
    
    
    
        public Board() {
    		addKeyListener(new TAdapter());
            setFocusable(true);
            setBackground(Color.BLACK);
            setDoubleBuffered(true);
            ingame = true;
    
            setSize(400, 300);
    		
    		craft = new Craft();
    		boss = new Boss(490, 0);
    
        }
    
        public void addNotify() {
            super.addNotify();
            B_WIDTH = getWidth();
            B_HEIGHT = getHeight();
    		animator = new Thread(this);
    		animator.start();
        }
    
    
        public void paint(Graphics g) {
            super.paint(g);
    
            if (ingame) {
    
                Graphics2D g2d = (Graphics2D)g;
    			
    			if (craft.isVisible())
                    g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(),
                                  this);
    
                ArrayList ms = craft.getMissiles();
    
                for (int i = 0; i < ms.size(); i++) {
                    Missile m = (Missile)ms.get(i);
                    g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);
    				}
    
    			if(boss.isVisible())
    				drawSprite(boss.getImage(), g2d ,boss.getX() , boss.getY(), 6, boss.getFrame(), 80, 184);
    
    
            } 
    
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }
    	
    
    	void drawSprite(Image source, Graphics2D g2d, int x, int y,
                         int columns, int frame, int width, int height){
    					
    		int frameX = (frame % columns) * width;
    		int frameY = (frame / columns) * height;
    		g2d.drawImage(source, x, y, x+width, y+height, frameX, frameY, frameX+width, frameY+height, this);
    	}
    	
    	public void cycle() {
    
            ArrayList ms = craft.getMissiles();
    
            for (int i = 0; i < ms.size(); i++) {
                Missile m = (Missile) ms.get(i);
                if (m.isVisible()) 
                    m.move();
                else ms.remove(i);
            }
    		if(boss.isVisible()) boss.move();
            craft.move();
            checkCollisions();  
        }
    	
    	public void checkCollisions(){        
    		
            ArrayList ms = craft.getMissiles();
    
            for (int i = 0; i < ms.size(); i++) {
                Missile m = (Missile) ms.get(i);
    
                Rectangle r1 = m.getBounds();			
    			Rectangle r4 = boss.getBounds();
    			//pixelPerfectCollision( , );
    			if(r1.intersects(r4)){
    				m.setVisible(false);
    				}
            }
        }
    	
    	public void run(){
    		long beforeTime, timeDiff, sleep;
    		
    		beforeTime = System.currentTimeMillis();
    		
    		while(true){
    			
    			cycle();
    			repaint();
    			
    			timeDiff = System.currentTimeMillis() - beforeTime;
    			sleep = DELAY - timeDiff;
    			
    			if(sleep < 0)
    				sleep = 2;
    			try{
    				Thread.sleep(sleep);
    				}catch (InterruptedException e){
    					System.out.println("interrupted");
    				}
    				
    			beforeTime = System.currentTimeMillis();
    		}
    	}
    	
    	private class TAdapter extends KeyAdapter {
    
            public void keyReleased(KeyEvent e) {
                craft.keyReleased(e);
            }
    
            public void keyPressed(KeyEvent e) {
                craft.keyPressed(e);
            }
        }
    }
    Java Code:
    package boss;
    
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.awt.image.ImageProducer;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    
    public class Boss{
    
    	private String boss = "Boss4.png";
    	
    	private int x;
    	private int y;
    	private int width;
    	private int height;
    	private boolean visible;
    	private BufferedImage image;
    	private boolean suund;
    	private boolean blink = true;
    	private int currentframe = 0;
    	private int sleep = 0;
    	private int blinksequence = 0;
    	private int[] sequence = {0,1,2,3,4,5,4,3,2,1};
    
    	
    	public Boss(int x, int y){
    		//BufferedImage image = null;
    		try{
    			image = ImageIO.read(new File(boss));
    		} catch (IOException e) {
            }
    		//ImageIcon ii = new ImageIcon(this.getClass().getResource(boss));
    		//image = ii.getSubimage(x, y,80,184);
    		width = image.getWidth(null);
    		height = image.getHeight(null);
    		visible = true;
    		suund = true;
    		this.x = x;
    		this.y = y;
    		}
    		
    	public void move(){
    		if(x < 0)
    			x = 400;
    		if(x > 320)
    			x -= 1;
    		if(y + height == 290)
    			suund = false;
    		if(y == 0)
    			suund = true;
    		if(suund)
    			y += 1;
    		if(suund == false)
    			y -= 1;
    		}
    		
    	public int getX(){
    		return x;
    		}
    		
    	public int getY(){
    		return y;
    		}
    	
    	public boolean isVisible(){
    		return visible;
    		}
    	
    	public void setVisible(Boolean visible){
    		this.visible = visible;
    		}
    		
    	public Image getImage(){
    		return image;
    		}
    		
    	public int getFrame(){
    			if(sleep == 8){
    				sleep = 0;
    				return sequence[nextframe()];
    				}
    			else{
    				sleep += 1;
    				return sequence[currentframe];
    				}
    			}
    
    		
    	public int nextframe(){
    		currentframe +=1;
    		if(currentframe >= sequence.length){
    			currentframe = 0;
    			blink = false;
    			}
    		return currentframe;
    		}
    	
    	public int getCurrentFrame(){
    		return currentframe;
    		}
    		
    	public Rectangle getBounds(){
    		return new Rectangle(x, y, width/6, height/1);
    		}
    	}
    This is where i tryed to use bufferedimage.

    Java Code:
    package boss;
    
    import java.awt.Image;
    
    import java.awt.Rectangle;
    
    import javax.swing.ImageIcon;
    
    public class Missile {
    
        private int x, y;
        private Image image;
        boolean visible;
        private int width, height;
    
        private final int BOARD_WIDTH = 390;
        private final int MISSILE_SPEED = 2;
    
        public Missile(int x, int y) {
    
            ImageIcon ii = new ImageIcon(this.getClass().getResource("missle.png"));
            image = ii.getImage();
            visible = true;
            width = image.getWidth(null);
            height = image.getHeight(null);
            this.x = x;
            this.y = y;
        }
    
    
        public Image getImage() {
            return image;
        }
    
        public int getX() {
            return x;
        }
    
        public int getY() {
            return y;
        }
    
        public boolean isVisible() {
            return visible;
        }
    
        public void setVisible(Boolean visible) {
            this.visible = visible;
        }
    
        public Rectangle getBounds() {
            return new Rectangle(x, y, width, height);
        }
    
        public void move() {
            x += MISSILE_SPEED;
            if (x > BOARD_WIDTH)
                visible = false;
        }
    }
    Java Code:
    package boss;
    
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.event.KeyEvent;
    
    import java.util.ArrayList;
    
    import javax.swing.ImageIcon;
    
    public class Craft {
    
        private String craft = "craft.png";
    
        private int dx;
        private int dy;
        private int x;
        private int y;
        private int width;
        private int height;
        private boolean visible;
        private Image image;
        private ArrayList<Missile> missiles;
    
    
        public Craft() {
            ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
            image = ii.getImage();
            width = image.getWidth(null);
            height = image.getHeight(null);
            missiles = new ArrayList<Missile>();
            visible = true;
            x = 40;
            y = 60;
        }
    
    
        public void move() {
    
            x += dx;
            y += dy;
    
            if (x < 1) {
                x = 1;
            }
    
            if (y < 1) {
                y = 1;
            }
        }
    
        public int getX() {
            return x;
        }
    
        public int getY() {
            return y;
        }
    
        public Image getImage() {
            return image;
        }
    
        public ArrayList<Missile> getMissiles() {
            return missiles;
        }
    
        public void setVisible(boolean visible) {
            this.visible = visible;
        }
    
        public boolean isVisible() {
            return visible;
        }
    
        public Rectangle getBounds() {
            return new Rectangle(x, y, width, height);
        }
    
        public void keyPressed(KeyEvent e) {
    
            int key = e.getKeyCode();
    
            if (key == KeyEvent.VK_SPACE) {
                fire();
            }
    
            if (key == KeyEvent.VK_LEFT) {
                dx = -1;
            }
    
            if (key == KeyEvent.VK_RIGHT) {
                dx = 1;
            }
    
            if (key == KeyEvent.VK_UP) {
                dy = -1;
            }
    
            if (key == KeyEvent.VK_DOWN) {
                dy = 1;
            }
        }
    
        public void fire() {
            missiles.add(new Missile(x + width, y + height/2));
        }
    
        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();
    
            if (key == KeyEvent.VK_LEFT) {
                dx = 0;
            }
    
            if (key == KeyEvent.VK_RIGHT) {
                dx = 0;
            }
    
            if (key == KeyEvent.VK_UP) {
                dy = 0;
            }
    
            if (key == KeyEvent.VK_DOWN) {
                dy = 0;
            }
        }
    }

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: cropping imageicon

    Start small. Prepare a a SSCCE (Short, Self Contained, Correct (Compilable), Example) that attempts to display one sprite of a spritesheet in a JLabel, using the two methods and one constructor I mentioned at #2.

    If that doesn't work, you have something small enough for us to analyze and help.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default Re: cropping imageicon

    I don't understand what this thread is al about; if you read the API documentation for the drawImge( ... ) methods, you'll see that two of them specify a rectangle of the image source to be drawn; there is no need to keep parts of the image as separate copies.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    Im trying to make pixelperfectcollision, and as much as i understand it, i need to use 1 sprite form my spritesheet. And stpe by step im gradually developing my code to a level where i have the basic classes for me to proceed. I started with using timer, then i madem ajor changes and went over to threads, now i see that iconimage is not the way to go for pixelperfectcollison, so now im trying to rewrite the code in bufferedimage.

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default Re: cropping imageicon

    I don't know what 'pixel perfect collision' is and I don't understand where Timers come in ... what I do know is that, if your images (or sprites) are quite 'fat', i.e. they almost completely fill up their bounding rectangle, a simple rect1.intersects(rect2) can do the job, especially if at least one of the images move quite fast on the screen (the user won't even see the inaccuracy).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: cropping imageicon

    Quote Originally Posted by JosAH View Post
    I don't understand what this thread is al about; if you read the API documentation for the drawImge( ... ) methods, you'll see that two of them specify a rectangle of the image source to be drawn; there is no need to keep parts of the image as separate copies.
    That's true, but can lead to cumbersome code and multiple repetitions of magic numbers or class constants in the drawing routine.

    BufferedImage#getSubimage(...) doesn't duplicate the image data, so shouldn't be computationally expensive, and IMO could yield cleaner code.
    The returned BufferedImage shares the same data array as the original image.
    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default Re: cropping imageicon

    Quote Originally Posted by DarrylBurke View Post
    That's true, but can lead to cumbersome code and multiple repetitions of magic numbers or class constants in the drawing routine.

    BufferedImage#getSubimage(...) doesn't duplicate the image data, so shouldn't be computationally expensive, and IMO could yield cleaner code.
    If the code becomes cluttered and ugly the programmer can't program himself out of a wet paper bag. Basically a rectangle from the image has to be drawn in/on a rectangle of the graphics area. You can do it with one method call; I wouldn't create a sub image for it as an in-between step, but who am I? ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    Pixelperfectcollision, it is basiclly the same as intersect method only that it compares pixels instead of recktangles. My shape fills up barely half of the rectangle that is created on it, so simple intersect wont work. Pixelperfectcollision compares the visibility of pixels, if both pixels under comparison are visible, then collision occurs.

    As for tehe subimage. I dont know it is the way to go, i justnknow that i need to compare one spesific frame from my spritesheet. And for that i either send the entire spritesheet to the pixelperfectcollision or do i sent that one specific frame to it.

  18. #18
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    I cant find a good guide to use the bufferedimage. There are all sorts of things, but none of them are using IMageIO.read. They use Imageicon and the make it into buffered imnage and son and so on. Could youu give me a good tutorial on how to use buffered image.

  19. #19
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    124
    Rep Power
    0

    Default Re: cropping imageicon

    Java Code:
    import java.awt.*; 
    import java.awt.event.*; 
    import java.awt.image.*; 
    import java.io.*; 
    import javax.imageio.*; 
    import javax.swing.*; 
    
    public class Bimage extends Component{
    
    	BufferedImage img;
    	
    	public void paint(Graphics g){
    		g.drawImage(img,0,0,null);
    		}
    	
    	public Bimage(){
    		try{
    			img = ImageIO.read(new File("Boss4.jpg"));
    			}catch(IOException e){}
    			}
    			
    	public Dimension getPreferredSize(){
    		if (img == null){
    			return new Dimension(100,100);
    			}else{
    				return new Dimension(img.getWidth(null), img.getHeight(null));
    				}
    			}
    			
    	public static void main(String[] args){
    		
    		JFrame f = new JFrame("Load Image Sample");
    		
    		f.addWindowListener(new WindowAdapter(){
    			public void windowClosing(WindowEvent e){
    				System.exit(0);
    				}
    			});
    			
    		f.add(new Bimage());
    		f.pack();
    		f.setVisible(true);
    		}
    	}
    Why doesent it show theimage i wnat it to show, i onl y get the 100X100 empty window

  20. #20
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default Re: cropping imageicon

    Are you sure the image loaded correctly (i.e. it isn't null)?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 0
    Last Post: 10-25-2011, 12:17 PM
  2. Cropping a BufferedImage
    By crikey in forum Advanced Java
    Replies: 2
    Last Post: 08-22-2010, 03:07 PM
  3. Image cropping
    By pads in forum AWT / Swing
    Replies: 3
    Last Post: 06-23-2010, 03:32 PM
  4. ImageIcon HELP!
    By ben1989 in forum New To Java
    Replies: 1
    Last Post: 05-05-2010, 08:48 PM
  5. Image cropping in Jsf on the release of mouse
    By HarshalAuro in forum JavaServer Faces (JSF)
    Replies: 0
    Last Post: 11-12-2008, 06:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •