Question

I'm trying to split up an image of a deck of cards and store an individual card into an Image.

Image image;
BufferedImage deck = ImageIO.read( new URL( "http://www.jfitz.com/cards/classic-playing-cards.png" ) );
image = deck.getSubimage( x, y, width, height );

incompatible types: BufferedImage cannot be converted to Image

Everywhere I've looked says that BufferedImage is an Image, this problem shouldn't exist. (Note: if this comes off looking like a class assignment, it is, but all we're supposed to do is load an image from a predetermined directory. I'm trying to take it a step further by using the URL for fun.)

EDIT 04/09/2014
I've been using different imports, so I guess the question I'm really trying to ask is how to convert a java.awt.image.BufferedImage to a java.scene.image.Image. Thanks for the help so far!

Was it helpful?

Solution

Once I knew what question to ask, google answered this really quickly. I found a quick fix on this blog.

BufferedImage tempCard = deck.getSubimage( x, y, width, height );
Image card = SwingFXUtils.toFXImage(tempCard, null );

Tried it out and works great!

OTHER TIPS

BufferedImage is a subclass of Image. You don't need to do any conversion.

You can just assign like:

Image image;
BufferedImage deck = ImageIO.read( new URL( "http://www.jfitz.com/cards/classic-playing-cards.png" ) );
image = deck;// That will do

A BufferedImage extends Image which means that you can declare a BufferedImage like so:

Image myImage = ImageIO.read(new URL("my/url"));

This starts getting into polymorphism and inheritance. Your object may be a BufferedImage, but a BufferedImage is still an Image and it can be used as one.

A more recognizable example perhaps would be instantiating an ArrayList as a List

List<MyType> aList = new ArrayList<>();

This allows this ArrayList to be compatible with all types of List objects, just like the BufferedImage.

Take a look at the API page for Image.

It lists all known subclasses of this abstract class, BufferedImage included. (There's only 2.)

Image image = new ImageIcon(bufferedImage).getImage();

That's the way I usually do it... OR

Image image = (Image) bufferedImage;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top