1

Please don't dislike this "generic question", since it really is a problem. I also searched other questions and the problem there was always that the people wanted to instantiate interfaces. That's not my case.

The class ColorModel is not an interface and has a constructor that takes an int. Why do I get an "Cannot instantiate the type ColorModel"-Error?

Here's the code:

package test;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class BufferedImageGetRGB {

    public static void main(String...args) {

        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("C:\\Users\\xxxxx\\Desktop\\testbinary.png"));
        } catch (IOException e) {}

        for (int y=0; y<img.getHeight(); ++y) {
            for (int x=0; x<img.getWidth(); ++x) {
                System.out.println(img.getRGB(y, x));
                ColorModel cm = new ColorModel(img.getRGB(y, x));
            }
        }
    }
}
0

1 Answer 1

4

You can't directly instantiate an object of the ColorModel type because this type is abstract as the ColorModel API will tell you, and same as interfaces, abstract types cannot be directly constructed. The API will also tell you the concrete subtypes that might be available. The lesson though here is that your question is quite similar to the interface type questions, and the solution is similar -- always check the API when you run into a such questions.

Note that you can get the image's ColorModel directly from the BufferedImage by calling its getColorModel() method. Not sure why you're trying to repeatedly create a new one in your for loop.

i.e.,

BufferedImage img = null;
try {
    img = ImageIO.read(new File("C:\\Users\\xxxxx\\Desktop\\testbinary.png"));
} catch (IOException e) {
   e.printStackTrace(); // never leave this block empty ********** 
   // exit program here?
}

ColorModel cm = img.getColorModel();

for (int y=0; y<img.getHeight(); ++y) {
    for (int x=0; x<img.getWidth(); ++x) {
        System.out.println(img.getRGB(y, x));
        // ColorModel cm = new ColorModel(img.getRGB(y, x));
    }
}

In a side note, this, catch (IOException e) {} is not a safe practice and hopefully your real code doesn't do this.

1
  • Oh man, I didn't see that it's abstract. This solves the problem. I checked the API, but the title said "Class ColorModel". Didn't expect that it could be abstract. Thanks +1
    – codepleb
    Feb 27, 2015 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.