I am extending the BufferedImage class, to add some method like getRed, getBlue, getGreen for getting pixel color. The problem is that my original image is BufferedImage object not my extended object. When I try to cast to extended datatype, it isnt working.
Sorry for my English
I get this error
Exception in thread "main" java.lang.ClassCastException: java.awt.image.BufferedImage cannot be cast to asciiart.EBufferedImage
Code where I am trying to cast from parent class
EBufferedImage character = (EBufferedImage)ImageClass.charToImage(letter, this.matrix_x, this.matrix_y);
My extended class
public class EBufferedImage extends BufferedImage
{
public EBufferedImage(int width, int height, int imageType)
{
super(width,height,imageType);
}
/**
* Returns the red component in the range 0-255 in the default sRGB
* space.
* @return the red component.
*/
public int getRed(int x, int y) {
return (getRGB(x, y) >> 16) & 0xFF;
}
/**
* Returns the green component in the range 0-255 in the default sRGB
* space.
* @return the green component.
*/
public int getGreen(int x, int y) {
return (getRGB(x, y) >> 8) & 0xFF;
}
/**
* Returns the blue component in the range 0-255 in the default sRGB
* space.
* @return the blue component.
*/
public int getBlue(int x, int y) {
return (getRGB(x, y) >> 0) & 0xFF;
}
}
You have a couple options:
Add a constructor to the extended class that accepts a
BufferedImageand sets everything appropriately.This one seems like a lot of work and potential for issues. If you forget to set some variable you could introduce some weird bugs, or lose information you need.
Create a wrapper class that has an instance of a
BufferedImage, and then add your methods in.This is pretty reasonable, and is not to diffcult. Make the
BufferedImagepublic or add a getter method and you can get the actualBufferedImageout of it if you need that.Create a Utility class that has your methods as being static and pass in the
BufferedImageas a parameter.Some people don’t like utility Classes, but I kind of like them for things like this. If you are going to use these methods all over the place, I think this is a good option.
Personally I would go the utility class route, but if you don’t like those then wrapping it as done in option 2 is just as functional.