1

I have a custom class vtools.Image that extends BufferedImage.

Then I am reading a picture from a url using ImageIO.read and sacing this as BufferedImage.

BufferedImage bfImg = ImageIO.read(imageUrl);

but then I would need to convert this bfImg into vtools.Image but when I try to cast it I am getting a ClassCastException error. What is the other way of converting these two?

Radek
  • 1,403
  • 3
  • 25
  • 54
  • Read this answer to a similar question. http://stackoverflow.com/questions/380813/downcasting-in-java – Danny Nov 21 '11 at 14:03

2 Answers2

2

EDIT: At first I thought, that you could simply write a special constructor, that takes a BufferedImage. But that is not that easy. So I would recommend to write a wrapper class like this:

package vtools;

import java.awt.image.BufferedImage;

public class Image {

    BufferedImage image;

    public Image(BufferedImage image) {
        this.image = image;
    }

    // Add your methods, that modify the image or return the result.
}
nfechner
  • 17,295
  • 7
  • 45
  • 64
  • when I do that an error shows up "no suitable constructor found for BufferedImage" since it extends BufferedImage and buffred image has a different constructor – Radek Nov 21 '11 at 15:18
  • I'm sorry, but you are right. There is no such constructor. After having a closer look at `BufferedImage`, I think, that you will need to change your approach. Instead of extending `BufferedImage`, you should write a wrapper class. I will update my answer to reflect that. – nfechner Nov 22 '11 at 08:52
1

ImageIO is from the core Java classes. It will have no idea how to read an image into your subclass. What you would need to do if you really want this is to have an extension of ImageIO (ie, you would have to subclass it, which I don't know is possible). Or you would have to have a vtools.Image constructor that takes a BufferredImage as parm and then pass that in.

Chris Aldrich
  • 1,904
  • 1
  • 22
  • 37