0

I wanted to make an spritesheet class for my java game . In past when i wanted to crop an image out of my spritesheet i used to use BufferedImage croping method , but its not working for me becuase i cant load the images when im loading images when they are in the jar file.

Now Im using Image Class . I searched an i found a crop method in Image class but i cant make it work .

what am i doing wrong ?

My SpriteSheet class :

package Maya.Core;

import java.awt.*;

public class Spritesheet{
    Texture sprite;
    public Spritesheet(String path){
        sprite = new Texture(path);     
    }

    public Image GetImage(Rect wantedRect){
        return sprite.image.crop(wantedRect.x,wantedRect.y,wantedRect.width,wantedRect.height);
    }    
}

My texture class:

public class Texture {
    public Image image;

    public Texture(String path) {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        URL imageResource = Window.class.getClassLoader().getResource(path);
        image = defaultToolkit.getImage(imageResource);
    }
}
Sepandi
  • 9
  • 1
  • 4
  • 1
    You can [load a resource as a `BufferedImage`](https://stackoverflow.com/a/17007533/6746785) and then [crop it](https://docs.oracle.com/en/java/javase/18/docs/api/java.desktop/java/awt/image/BufferedImage.html#getSubimage(int,int,int,int)). – gthanop Sep 11 '22 at 06:31
  • I know but my whole game uses Image class on java.awt.Image . is there any way to do it with java.awt.Image class , not with buffered image ? – Sepandi Sep 11 '22 at 06:34
  • `BufferedImage` is an `Image`. That is, `BufferedImage` extends `Image`, so a `BufferedImage` can be used wherever `Image` would. – gthanop Sep 11 '22 at 06:34
  • how can i convert BufferedImage Object to Image ? casting isn't working – Sepandi Sep 11 '22 at 06:35
  • What type is your `Image` class? Is it `java.awt.Image` or something else? Because I can see you are using method `crop` on it, which doesn't exist on a `java.awt.Image` until JDK 18. – gthanop Sep 11 '22 at 06:42
  • you mean if i use jdk 18 it will work ? – Sepandi Sep 11 '22 at 06:46
  • No. I mean it will not work on any JDK, because as far as I know `java.awt.Image` doesn't have method `crop` in it. – gthanop Sep 11 '22 at 06:48
  • oh ok thanks . as you said i tried to convert all of my java.awt.Image s to BufferedImage s with casting but i get an error : ``` Caused by: java.lang.ClassCastException: class sun.awt.image.ToolkitImage cannot be cast to class java.awt.image.BufferedImage (sun.awt.image.ToolkitImage and java.awt.image.BufferedImage are in module java.desktop of loader 'bootstrap')``` – Sepandi Sep 11 '22 at 06:53
  • Actually I said you can load a resource directly as a `BufferedImage` (see the first link in my first comment). Then I said that `BufferedImage`s work wherever `Image`s do (because `BufferedImage` is already an `Image`). And finally I said that `crop` method does not exist on any `Image`. – gthanop Sep 11 '22 at 06:59

0 Answers0