2

遵循@PhiLho 对如何将 BufferedImage 转换为 8 位的回答的想法?,我想用来ColorQuantizerDescriptor转换一个BufferedImage,imageType TYPE_INT_RGB,但是RenderedOp#getColorModel()抛出以下异常:

java.lang.IllegalArgumentException:指定的 ColorModel 与图像 SampleModel 不兼容。
    在 javax.media.jai.PlanarImage.setImageLayout(PlanarImage.java:541)
    在 javax.media.jai.RenderedOp.createRendering(RenderedOp.java:878)
    在 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

4

1 回答 1

3

The following example has been modified from 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);
            }
        });
    }
}

Works for me:Using octree

Edit: tried with your median cut and seems to work as well, though much slower.

Using median cut

于 2013-03-09T17:34:08.107 回答