简体   繁体   中英

Use ImageIO.read for class extending BufferedImage

(what people have against hello?)

I have a class which extends BufferedImage :

public class NamedImage extends BufferedImage{
    String name;
    public NamedImage(int width, int height, int imageType) {
        super(width, height, imageType);
    }
    public void setName(String text){
        name = text;
    }
}

Before I had this, I got my Images with:

Image image = ImageIO.read(res);

Now, I want to translate this to NamedImage , but the following tries don't work:

NamedImage image = ImageIO.read(res);
NamedImage image = (NamedImage) ImageIO.read(res);

How can I achieve what I want to do? Why can't I cast a buffered image into a class, which extends this custom class?

(what people have against thank you?)

You can cast an instance of a subclass to its parent class. But you cannot cast an instance of a superclass to a subclass

You can try to use solution something like this:

public class NamedImage extends BufferedImage {

    private String name;

    public NamedImage(BufferedImage img,String name){
        super(img.getWidth(),img.getHeight(),img.getType());
        setData(img.getData());
        this.name=name;
    }


    public NamedImage(int width, int height, int imageType) {
        super(width, height, imageType);

    }

    public void setName(String text) {
        name = text;
    }

    public static void main(String args[]) throws IOException {
        NamedImage image = new NamedImage(ImageIO.read(new File("/Users/igor/Downloads/cats-coloring.gif")),"A cat");

    }
}

How can I achieve what I want to do?

NamedImage should have a constructor that accepts a BufferedImage and a String .

Alternately, add the images to a map that uses the name as key. EG

BufferedImage bi = //...
String name = //...
HashMap<String, BufferedImage> images = HashMap<String, BufferedImage>();
images.add(name, bi);

Here's a possibility, if you want ImageIO to use your specific subclass. However, if all you want to do is give it a name, I'd probably use @AndrewThompsons suggestion with a Map<String, BufferedImage> , because it's less verbose.

ImageInputStream stream = ImageIO.createImageInputStream(res);
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);

if (readers.hasNext()) {
    ImageReader reader = readers.next();
    reader.setInput(reader);

    int w = reader.getWidth(0);
    int h = reader.getHeight(0);

    ImageReadParam param = reader.getDefaultReadParam();

    NamedImage image = new NamedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    param.setDestination(image);

    /*image = (NamedImage)*/ reader.read(0, param);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM