如何使用ColorQuantizerDescriptor?

时间:2013-03-09 16:16:52

标签: java bmp javax.imageio jai quantization

根据@PhiLho's answer to How to convert a BufferedImage to 8 bit?的想法,我想使用ColorQuantizerDescriptor转换BufferedImage,imageType TYPE_INT_RGB,但RenderedOp#getColorModel()会抛出以下异常:

java.lang.IllegalArgumentException: The specified ColorModel is incompatible with the image SampleModel.
    at javax.media.jai.PlanarImage.setImageLayout(PlanarImage.java:541)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:878)
    at javax.media.jai.RenderedOp.getColorModel(RenderedOp.java:2253)

这是我尝试使用的代码:

final RenderedOp medianCutQuantizerOp = ColorQuantizerDescriptor.create(rgbImage, ColorQuantizerDescriptor.MEDIANCUT, 256, null, null, null, null, null);
final BufferedImage bi = medianCutQuantizerOp.getAsBufferedImage(null, medianCutQuantizerOp.getColorModel());

如何使用ColorQuantizerDescriptor

1 个答案:

答案 0 :(得分:3)

以下示例已从http://code.google.com/p/color-reduction-experiments/source/browse/trunk/it/geosolutions/mapproducers/MapProducersTest.java?r=2

进行了修改
public class Main {
    public static void main(String[] args) throws Exception {

        BufferedImage original = ImageIO.read(new File("/Users/Nick/Desktop/with_flowers.jpg"));
         // 300 seems to be a good number
        final RenderedOp cqImage = ColorQuantizerDescriptor.create(
           original, ColorQuantizerDescriptor.OCTTREE,
           new Integer(255), new Integer(300), null, new Integer(2),
           new Integer(2), null);

        assert cqImage.getColorModel() instanceof IndexColorModel;
        final BufferedImage converted = cqImage.getAsBufferedImage();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final JFrame f = new JFrame();
                f.setTitle("Test");
                f.getContentPane().add((new ScrollingImagePanel(converted, 300, 300)));
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

适合我:Using octree

编辑:尝试使用中位数切割并且似乎也能正常工作,但速度要慢得多。

Using median cut