我有TIFF
256字节调色板。在Java中,我将此TIFF
读到BufferedImage
。此BufferedImage
有IndexColorModel
。当我遍历BufferedImage
中的像素时,我只能获得RGB。我想编写方法,x,y
使用BufferedImage
从调色板获取原始颜色索引(不是RGB颜色,只是来自TIFF
调色板的原始索引)。我怎样才能做到这一点?
我知道我可以遍历IndexColorModel并检查RBG相等,但是如果TIFF
至少有2个具有相同颜色的索引(例如索引0 - 黑色,132 - 黑色;假设,像素10x10有黑色[rgb=0,0,0]
- 然后我不知道我应该采用哪个索引 - 它们具有相同的RGB值)。
我还可以读取原始TIFF
,然后计算字节数组中的像素位置,但我不想这样做 - 我想使用JAI
中的内容。
对于没有外部库的BufferedImage
和JAI
,有没有办法做到这一点?
由于
答案 0 :(得分:4)
好的,那么你可以获得
并获取此数据数组中实际使用的索引。
此示例读取索引,在颜色模型中查找相应的颜色,并将结果写入“标准”BufferedImage(仅作为验证)
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.IndexColorModel;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class IndexedBufferedImage
{
public static void main(String[] args) throws IOException
{
BufferedImage image = ImageIO.read(new File("exampleTiff256.tif"));
System.out.println(image);
System.out.println(image.getColorModel());
ColorModel colorModel = image.getColorModel();
IndexColorModel indexColorModel = null;
if (colorModel instanceof IndexColorModel)
{
indexColorModel = (IndexColorModel)colorModel;
}
else
{
System.out.println("No IndexColorModel");
return;
}
DataBuffer dataBuffer = image.getRaster().getDataBuffer();
DataBufferByte dataBufferByte = null;
if (dataBuffer instanceof DataBufferByte)
{
dataBufferByte = (DataBufferByte)dataBuffer;
}
else
{
System.out.println("No DataBufferByte");
return;
}
int w = image.getWidth();
int h = image.getHeight();
BufferedImage test = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
byte data[] = dataBufferByte.getData();
for (int y=0; y<h; y++)
{
for (int x=0; x<w; x++)
{
int arrayIndex = x + y * w;
int colorIndex = data[arrayIndex];
int color = indexColorModel.getRGB(colorIndex);
System.out.println("At "+x+" "+y+" index is "+colorIndex+
" with color "+Integer.toHexString(color));
test.setRGB(x, y, color);
}
}
ImageIO.write(test, "PNG", new File("exampleTiff256.png"));
}
}