Order of channels in BufferedImage?

陌路散爱 提交于 2019-12-25 13:46:30

问题


How do I find out the order of color channels in a BufferedImage (different types including alpha channels)?

I need to know the order of R, G, and B parameters for operations like LookupOp (order of byte[][] in ByteLookupTable(int, byte[][])) or RescaleOp(float[], float[], hints).

Is there a generic way to find the order from a given BufferedImage? I thought it should be in the ColorModel but I can't find it.

I have used code like if (t == BufferedImage.TYPE_INT_ARGB) but there must be better ways, right?


回答1:


I think what you're looking for is split between SampleModel and ColorModel.

The SampleModel describes how the data is organized which allows you to get the data for one or more pixels. (You get a SampleModel by calling bi.getData().getSampleModel(), where bi is a BufferedImage).

ColorModel then provides methods (getAlpha, getRed, getGreen, GetBlue) for getting the ARGB components from a pixel.

Addendum:

I think the way you use this is:

    BufferedImage bi = ...;
    Raster r = bi.getData();
    // Use the sample model to get the pixel
    SampleModel sm = r.getSampleModel();
    Object pixel = sm.getPixel(0, 0, (int[])null, r.getDataBuffer());
    // Use the color model to get the red value from the pixel
    ColorModel cm = bi.getColorModel();
    int red = cm.getRed(pixel[0]);

This looks like it would be very flexible for handling any color/sample model you may encounter, but I can't imagine the performance would be spectacular. I'd probably use this model agnostic approach to convert the image to TYPE_INT_ARGB where the layout is well documented, then manipulate the data directly. Then, if necessary, convert it back to the original form.



来源:https://stackoverflow.com/questions/5170321/order-of-channels-in-bufferedimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!