ngageoint / tiff-java

Tagged Image File Format Java Library
https://ngageoint.github.io/tiff-java
MIT License
72 stars 33 forks source link

? about retrieveing pixel data.. #4

Closed BradWalker closed 7 years ago

BradWalker commented 7 years ago

I have a quick question about the Geopackages TIFF library. I'm having a real bear of a time trying to figure out how to create a BufferedImage for display on the screen.

It seems to me that once I execute the following

Rasters rasters = fileDirectory.readRasters();

I then have to do something like the following to retrieve the pixel values and then put the value into my graphic image.

        for (int i = 0; i < rasters.getSampleValues().length; i++) {
            for (int j = 0; j < rasters.getSampleValues()[i].length; j++) {
                "pixeldata" = rasters.getSampleValues()[i][j];
            }
        }

There really is no way to actually read a java.awt.image.BufferedImage or java.awt.Image from from the Rasters class..

Correct?

bosborn commented 7 years ago

Hi Brad,

There is nothing built into this library for converting to BufferedImages. We use this library for both Java and Android libraries, so need to avoid awt classes. Based upon your specific case (PhotometricInterpretation of Palette color, ColorMap, 8 bits per sample, etc), the following creates a same size BufferedImage and writes a jpeg file. You could modify and optimize as needed. You would also need additional logic to handle multiple types of TIFF images.

List<Integer> colorMap = fileDirectory.getColorMap();
int colorMapEntries = colorMap.size() / 3;
byte[] cmap = new byte[colorMap.size()];
for (int i = 0; i < colorMap.size(); i++) {
    byte colorValue = (byte) Math
            .round((colorMap.get(i) / 65535f) * 255f);
    int colorIndex = (i % colorMapEntries) * 3 + (i / colorMapEntries);
    cmap[colorIndex] = colorValue;
}
IndexColorModel colorModel = new IndexColorModel(rasters
        .getBitsPerSample().get(0), colorMapEntries, cmap, 0, false);

int width = rasters.getWidth();
int height = rasters.getHeight();
BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_BYTE_INDEXED, colorModel);
WritableRaster writableRaster = image.getRaster();
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        byte pixelValue = rasters.getPixelSample(0, x, y).byteValue();
        byte data[] = new byte[] { pixelValue };
        writableRaster.setDataElements(x, y, data);
    }
}

ImageIO.write(image, "jpeg", new File("image.jpeg"));

Scaled down version of the drawn jpeg file. image