Example usage for java.awt.image BufferedImage getRaster

List of usage examples for java.awt.image BufferedImage getRaster

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getRaster.

Prototype

public WritableRaster getRaster() 

Source Link

Document

Returns the WritableRaster .

Usage

From source file:org.openqa.selenium.TakesScreenshotTest.java

private Set<String> getColors(BufferedImage image, final int stepX, final int stepY) throws IOException {
    Set<String> colors = new TreeSet<String>();

    int height = image.getHeight();
    int width = image.getWidth();
    assertTrue(width > 0);/*from   www. ja v  a2s  .com*/
    assertTrue(height > 0);

    Raster raster = image.getRaster();
    String hex = "";
    int color = 0;
    for (int i = 0; i < width; i = i + stepX) {
        for (int j = 0; j < height; j = j + stepY) {
            hex = String.format("#%02x%02x%02x", (raster.getSample(i, j, 0)), (raster.getSample(i, j, 1)),
                    (raster.getSample(i, j, 2)));
            colors.add(hex);
        }
    }
    return colors;
}

From source file:tilt.image.Picture.java

/**
 * Convert from greyscale to twotone (black and white)
 * Adapted from OCRopus/*w ww  .  jav  a2  s. c  om*/
 * Copyright 2006-2008 Deutsches Forschungszentrum fuer Kuenstliche 
 * Intelligenz or its licensors, as applicable.
 * http://ocropus.googlecode.com/svn/trunk/ocr-binarize/ocr-binarize-sauvola.cc
 * @throws Exception 
 */
void convertToTwoTone() throws ImageException {
    try {
        int MAXVAL = 256;
        double k = 0.34;
        if (greyscale == null)
            convertToGreyscale();
        BufferedImage grey = ImageIO.read(greyscale);
        WritableRaster grey_image = grey.getRaster();
        WritableRaster bin_image = grey.copyData(null);
        int square = (int) Math.floor(grey_image.getWidth() * 0.025);
        if (square == 0)
            square = Math.min(20, grey_image.getWidth());
        if (square > grey_image.getHeight())
            square = grey_image.getHeight();
        int whalf = square >> 1;
        if (whalf == 0)
            throw new Exception("whalf==0!");
        int image_width = grey_image.getWidth();
        int image_height = grey_image.getHeight();
        // Calculate the integral image, and integral of the squared image
        // original algorithm ate up too much memory, use floats for longs
        float[][] integral_image = new float[image_width][image_height];
        float[][] rowsum_image = new float[image_width][image_height];
        float[][] integral_sqimg = new float[image_width][image_height];
        float[][] rowsum_sqimg = new float[image_width][image_height];
        int xmin, ymin, xmax, ymax;
        double diagsum, idiagsum, diff, sqdiagsum, sqidiagsum, sqdiff, area;
        double mean, std, threshold;
        // for get/setPixel
        int[] iArray = new int[1];
        int[] oArray = new int[1];
        for (int j = 0; j < image_height; j++) {
            grey_image.getPixel(0, j, iArray);
            rowsum_image[0][j] = iArray[0];
            rowsum_sqimg[0][j] = iArray[0] * iArray[0];
        }
        for (int i = 1; i < image_width; i++) {
            for (int j = 0; j < image_height; j++) {
                grey_image.getPixel(i, j, iArray);
                rowsum_image[i][j] = rowsum_image[i - 1][j] + iArray[0];
                rowsum_sqimg[i][j] = rowsum_sqimg[i - 1][j] + iArray[0] * iArray[0];
            }
        }
        for (int i = 0; i < image_width; i++) {
            integral_image[i][0] = rowsum_image[i][0];
            integral_sqimg[i][0] = rowsum_sqimg[i][0];
        }
        for (int i = 0; i < image_width; i++) {
            for (int j = 1; j < image_height; j++) {
                integral_image[i][j] = integral_image[i][j - 1] + rowsum_image[i][j];
                integral_sqimg[i][j] = integral_sqimg[i][j - 1] + rowsum_sqimg[i][j];
            }
        }
        // compute mean and std.dev. using the integral image
        for (int i = 0; i < image_width; i++) {
            for (int j = 0; j < image_height; j++) {
                xmin = Math.max(0, i - whalf);
                ymin = Math.max(0, j - whalf);
                xmax = Math.min(image_width - 1, i + whalf);
                ymax = Math.min(image_height - 1, j + whalf);
                area = (xmax - xmin + 1) * (ymax - ymin + 1);
                grey_image.getPixel(i, j, iArray);
                // area can't be 0 here
                if (area == 0)
                    throw new Exception("area can't be 0 here!");
                if (xmin == 0 && ymin == 0) {
                    // Point at origin
                    diff = integral_image[xmax][ymax];
                    sqdiff = integral_sqimg[xmax][ymax];
                } else if (xmin == 0 && ymin != 0) {
                    // first column
                    diff = integral_image[xmax][ymax] - integral_image[xmax][ymin - 1];
                    sqdiff = integral_sqimg[xmax][ymax] - integral_sqimg[xmax][ymin - 1];
                } else if (xmin != 0 && ymin == 0) {
                    // first row
                    diff = integral_image[xmax][ymax] - integral_image[xmin - 1][ymax];
                    sqdiff = integral_sqimg[xmax][ymax] - integral_sqimg[xmin - 1][ymax];
                } else {
                    // rest of the image
                    diagsum = integral_image[xmax][ymax] + integral_image[xmin - 1][ymin - 1];
                    idiagsum = integral_image[xmax][ymin - 1] + integral_image[xmin - 1][ymax];
                    diff = diagsum - idiagsum;
                    sqdiagsum = integral_sqimg[xmax][ymax] + integral_sqimg[xmin - 1][ymin - 1];
                    sqidiagsum = integral_sqimg[xmax][ymin - 1] + integral_sqimg[xmin - 1][ymax];
                    sqdiff = sqdiagsum - sqidiagsum;
                }
                mean = diff / area;
                std = Math.sqrt((sqdiff - diff * diff / area) / (area - 1));
                threshold = mean * (1 + k * ((std / 128) - 1));
                if (iArray[0] < threshold)
                    oArray[0] = 0;
                else
                    oArray[0] = MAXVAL - 1;
                bin_image.setPixel(i, j, oArray);
            }
        }
        twotone = File.createTempFile(PictureRegistry.PREFIX, PictureRegistry.SUFFIX);
        grey.setData(bin_image);
        ImageIO.write(grey, "png", twotone);
    } catch (Exception e) {
        throw new ImageException(e);
    }
}

From source file:tilt.image.page.Page.java

/**
 * Print the word shapes over the top of the original image
 * @param original the original raster to write to
 *///from  www  . ja  va2 s. c o m
public void drawShapes(BufferedImage original) {
    Graphics g = original.getGraphics();
    for (int i = 0; i < lines.size(); i++) {
        Line l = lines.get(i);
        l.print(g, original.getRaster(), i + 1);
    }
}

From source file:de.fhg.igd.swingrcp.SwingRCPUtilities.java

/**
 * Convert a SWT Image to a {@link BufferedImage}
 * /*from  w w  w .  j  ava  2s.  c  o  m*/
 * {@link "http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet156.java?view=co"}
 * 
 * @param data the SWT {@link ImageData}
 * @param applyAlphaMask true if the image data's alpha mask should be
 *            applied to the result image (if there is any). This method
 *            calls {@link #applyTransparencyMask(BufferedImage, ImageData)}
 *            for that purpose.
 * @return the AWT {@link BufferedImage}
 */
public static BufferedImage convertToAWT(ImageData data, boolean applyAlphaMask) {
    ColorModel colorModel = null;
    PaletteData palette = data.palette;

    BufferedImage result;
    if (palette.isDirect) {
        colorModel = new DirectColorModel(data.depth, palette.redMask, palette.greenMask, palette.blueMask);
        BufferedImage bufferedImage = new BufferedImage(colorModel,
                colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                int pixel = data.getPixel(x, y);
                RGB rgb = palette.getRGB(pixel);
                bufferedImage.setRGB(x, y, rgb.red << 16 | rgb.green << 8 | rgb.blue);
            }
        }
        result = bufferedImage;
    } else {
        RGB[] rgbs = palette.getRGBs();
        byte[] red = new byte[rgbs.length];
        byte[] green = new byte[rgbs.length];
        byte[] blue = new byte[rgbs.length];
        for (int i = 0; i < rgbs.length; i++) {
            RGB rgb = rgbs[i];
            red[i] = (byte) rgb.red;
            green[i] = (byte) rgb.green;
            blue[i] = (byte) rgb.blue;
        }
        if (data.transparentPixel != -1) {
            colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue, data.transparentPixel);
        } else {
            colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue);
        }
        BufferedImage bufferedImage = new BufferedImage(colorModel,
                colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
        WritableRaster raster = bufferedImage.getRaster();
        int[] pixelArray = new int[1];
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                int pixel = data.getPixel(x, y);
                pixelArray[0] = pixel;
                raster.setPixel(x, y, pixelArray);
            }
        }
        result = bufferedImage;
    }

    if (data.getTransparencyType() == SWT.TRANSPARENCY_MASK && applyAlphaMask) {
        result = applyTransparencyMask(result, data.getTransparencyMask());
    }
    return result;
}

From source file:org.csa.rstb.dat.toolviews.HaAlphaPlotPanel.java

private void toggleColor() {
    BufferedImage image = plot.getImage();
    if (image != null) {
        if (!plotColorsInverted) {
            image = new BufferedImage(untoggledColorModel, image.getRaster(), image.isAlphaPremultiplied(),
                    null);/* w ww  .j a v a2 s .co  m*/
        } else {
            image = new BufferedImage(toggledColorModel, image.getRaster(), image.isAlphaPremultiplied(), null);
        }
        plot.setImage(image);
        densityPlotDisplay.getChart().setNotify(true);
        plotColorsInverted = !plotColorsInverted;
    }
}

From source file:javafx1.JavaFX1.java

private void bildSchleife() {
        File f = new File("F:/NetBeansProjekte/pictures");
        File[] fileArray = f.listFiles();
        java.util.Arrays.sort(fileArray);
        for (File file : fileArray) {
            try {
                System.out.println("file: " + file.getCanonicalPath());
                BufferedImage bi = ImageIO.read(file);
                String s = encodeToString(bi, "jpg");

                // System.out.println(" enc" + encodeToString(bi, "jpg").substring(0, 10));
                byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();

                //byte[] xx = base64String.getBytes(StandardCharsets.UTF_8);
                // bild, wie es von http kommt
                RunPic rp = new RunPic(this, s.getBytes());
                Platform.runLater(rp);/*from   w w  w  . j a v a 2 s .  c o  m*/
                try {
                    Thread.sleep(550);
                    //break;
                } catch (InterruptedException ex) {
                    Logger.getLogger(JavaFX1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(JavaFX1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

From source file:javafx1.JavaFX1.java

private Image analyzePic(BufferedImage bi) {
        //System.out.println("height:" + bi.getHeight() + ", width:" + bi.getWidth());
        //bi = bi.getSubimage(100, 100, 50, 50);
        // Originalbild nach MAT
        byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
        Mat matOrigin = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
        matOrigin.put(0, 0, data);/*w w w .j a  va  2s  .c o  m*/
        //+Core.addWeighted();
        //+Imgproc.threshold(matOrigin, matOrigin, thresh, maxval, type)
        //+Core.bitwise_xor(matOrigin, matOrigin, matOrigin);

        // fr graubild
        Mat matManipulate = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC1);
        // in Graubild wandeln von...nach
        // Imgproc.cvtColor(matOrigin, matManipulate, Imgproc.COLOR_BGR2GRAY);
        // Imgproc.blur(matManipulate, matManipulate, new Size(3, 3));
        matManipulate = doCanny(matOrigin);
        //aus Mat in BufferedImagae zurckwandeln
        //  byte[] data1 = new byte[matManipulate.rows() * matManipulate.cols() * (int) (matManipulate.elemSize())];
        //  matManipulate.get(0, 0, data1);
        //  BufferedImage biManipulate = new BufferedImage(matManipulate.cols(), matManipulate.rows(), BufferedImage.TYPE_BYTE_GRAY);
        //  biManipulate.getRaster().setDataElements(0, 0, matManipulate.cols(), matManipulate.rows(), data1);
        // BufferedImage gray = image1.getSubimage(0, 0, image1.getTileWidth(), image1.getHeight());
        //return biManipulate;
        matManipulate = doBackgroundRemoval(matManipulate);
        Rect r = new Rect(230, 10, 55, 40);
        Mat m = new Mat(matOrigin, r);
        //return mat2Image(matOrigin);
        return mat2Image(m);

    }

From source file:org.geoserver.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testMosaicHoles() throws Exception {
    String url = "wms?LAYERS=sf%3Amosaic_holes&FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1"
            + "&REQUEST=GetMap&STYLES=&SRS=EPSG%3A4326"
            + "&BBOX=6.40284375,36.385494140625,12.189662109375,42.444494140625"
            + "&WIDTH=489&HEIGHT=512&transparent=true";
    BufferedImage bi = getAsImage(url, "image/png");
    int[] pixel = new int[4];
    bi.getRaster().getPixel(0, 250, pixel);
    assertTrue(Arrays.equals(new int[] { 0, 0, 0, 255 }, pixel));

    // now reconfigure the mosaic for transparency
    CoverageInfo ci = getCatalog().getCoverageByName("sf:mosaic_holes");
    Map<String, Serializable> params = ci.getParameters();
    params.put(ImageMosaicFormat.INPUT_TRANSPARENT_COLOR.getName().getCode(), "#000000");
    params.put(ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR.getName().getCode(), "#000000");
    getCatalog().save(ci);//from w  ww  .ja  va 2 s . c o m

    // this time that pixel should be transparent
    bi = getAsImage(url, "image/png");
    bi.getRaster().getPixel(0, 250, pixel);
    assertTrue(Arrays.equals(new int[] { 255, 255, 255, 0 }, pixel));
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static RegularField bufferedImage2RegularField(BufferedImage inImage, boolean vFlip) {
    if (inImage == null) {
        return null;
    }/*w w  w.  ja  va2s.c  o m*/

    int[] dims = new int[2];
    dims[0] = inImage.getWidth();
    dims[1] = inImage.getHeight();

    RegularField field = new RegularField(dims);

    WritableRaster raster = inImage.getRaster();
    byte[][] samples = null;
    int[][] samples32 = null;
    int i = 0;
    switch (inImage.getType()) {
    case BufferedImage.TYPE_BYTE_GRAY:
        samples = new byte[1][];
        samples[0] = new byte[dims[0] * dims[1]];
        if (vFlip) {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i++] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                }
            }
        } else {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i++] = (byte) raster.getSample(x, y, 0);
                }
            }
        }
        field.addData(DataArray.create(samples[0], 1, "grayscaleData"));
        break;
    case BufferedImage.TYPE_USHORT_GRAY:
        samples32 = new int[1][];
        samples32[0] = new int[dims[0] * dims[1]];
        if (vFlip) {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples32[0][i++] = (int) raster.getSample(x, dims[1] - y - 1, 0);
                }
            }
        } else {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples32[0][i++] = (int) raster.getSample(x, y, 0);
                }
            }
        }
        field.addData(DataArray.create(samples32[0], 1, "grayscaleData"));
        break;
    case BufferedImage.TYPE_INT_RGB:
        samples = new byte[3][];
        samples[0] = new byte[dims[0] * dims[1]];
        samples[1] = new byte[dims[0] * dims[1]];
        samples[2] = new byte[dims[0] * dims[1]];
        if (vFlip) {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                    samples[1][i] = (byte) raster.getSample(x, dims[1] - y - 1, 1);
                    samples[2][i] = (byte) raster.getSample(x, dims[1] - y - 1, 2);
                    i++;
                }
            }
        } else {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, y, 0);
                    samples[1][i] = (byte) raster.getSample(x, y, 1);
                    samples[2][i] = (byte) raster.getSample(x, y, 2);
                    i++;
                }
            }
        }
        field.addData(DataArray.create(samples[0], 1, "redData"));
        field.addData(DataArray.create(samples[1], 1, "greenData"));
        field.addData(DataArray.create(samples[2], 1, "blueData"));
        break;
    case BufferedImage.TYPE_3BYTE_BGR:
    case BufferedImage.TYPE_INT_BGR:
        samples = new byte[3][];
        samples[0] = new byte[dims[0] * dims[1]];
        samples[1] = new byte[dims[0] * dims[1]];
        samples[2] = new byte[dims[0] * dims[1]];
        if (vFlip) {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                    samples[1][i] = (byte) raster.getSample(x, dims[1] - y - 1, 1);
                    samples[2][i] = (byte) raster.getSample(x, dims[1] - y - 1, 2);
                    i++;
                }
            }
        } else {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, y, 0);
                    samples[1][i] = (byte) raster.getSample(x, y, 1);
                    samples[2][i] = (byte) raster.getSample(x, y, 2);
                    i++;
                }
            }
        }
        field.addData(DataArray.create(samples[0], 1, "blueData"));
        field.addData(DataArray.create(samples[1], 1, "greenData"));
        field.addData(DataArray.create(samples[2], 1, "redData"));
        break;
    case BufferedImage.TYPE_INT_ARGB:
        samples = new byte[4][];
        samples[0] = new byte[dims[0] * dims[1]];
        samples[1] = new byte[dims[0] * dims[1]];
        samples[2] = new byte[dims[0] * dims[1]];
        samples[3] = new byte[dims[0] * dims[1]];
        for (int y = 0; y < dims[1]; y++) {
            for (int x = 0; x < dims[0]; x++) {
                samples[0][i] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                samples[1][i] = (byte) raster.getSample(x, dims[1] - y - 1, 1);
                samples[2][i] = (byte) raster.getSample(x, dims[1] - y - 1, 2);
                samples[3][i] = (byte) raster.getSample(x, dims[1] - y - 1, 3);
                i++;
            }
        }
        field.addData(DataArray.create(samples[0], 1, "redData"));
        field.addData(DataArray.create(samples[1], 1, "greenData"));
        field.addData(DataArray.create(samples[2], 1, "blueData"));
        field.addData(DataArray.create(samples[3], 1, "alphaData"));
        break;
    case BufferedImage.TYPE_4BYTE_ABGR:
        samples = new byte[4][];
        samples[0] = new byte[dims[0] * dims[1]];
        samples[1] = new byte[dims[0] * dims[1]];
        samples[2] = new byte[dims[0] * dims[1]];
        samples[3] = new byte[dims[0] * dims[1]];
        for (int y = 0; y < dims[1]; y++) {
            for (int x = 0; x < dims[0]; x++) {
                samples[0][i] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                samples[1][i] = (byte) raster.getSample(x, dims[1] - y - 1, 1);
                samples[2][i] = (byte) raster.getSample(x, dims[1] - y - 1, 2);
                samples[3][i] = (byte) raster.getSample(x, dims[1] - y - 1, 3);
                i++;
            }
        }
        field.addData(DataArray.create(samples[0], 1, "alphaData"));
        field.addData(DataArray.create(samples[1], 1, "redData"));
        field.addData(DataArray.create(samples[2], 1, "greenData"));
        field.addData(DataArray.create(samples[3], 1, "blueData"));
        break;
    default:
        BufferedImage newImg = new BufferedImage(inImage.getWidth(), inImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = newImg.createGraphics();
        g2d.drawImage(inImage, null, 0, 0);
        g2d.dispose();
        raster = newImg.getRaster();
        samples = new byte[3][];
        samples[0] = new byte[dims[0] * dims[1]];
        samples[1] = new byte[dims[0] * dims[1]];
        samples[2] = new byte[dims[0] * dims[1]];
        if (vFlip) {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, dims[1] - y - 1, 0);
                    samples[1][i] = (byte) raster.getSample(x, dims[1] - y - 1, 1);
                    samples[2][i] = (byte) raster.getSample(x, dims[1] - y - 1, 2);
                    i++;
                }
            }
        } else {
            for (int y = 0; y < dims[1]; y++) {
                for (int x = 0; x < dims[0]; x++) {
                    samples[0][i] = (byte) raster.getSample(x, y, 0);
                    samples[1][i] = (byte) raster.getSample(x, y, 1);
                    samples[2][i] = (byte) raster.getSample(x, y, 2);
                    i++;
                }
            }
        }
        field.addData(DataArray.create(samples[0], 1, "redData"));
        field.addData(DataArray.create(samples[1], 1, "greenData"));
        field.addData(DataArray.create(samples[2], 1, "blueData"));
    }

    float[][] affine = new float[4][3];
    for (int j = 0; j < 3; j++) {
        for (int k = 0; k < 3; k++) {
            affine[j][k] = 0.0f;
            if (j == k)
                affine[j][k] = 1.0f;
        }
    }

    affine[3][0] = -(float) dims[0] / 2.0f;
    affine[3][1] = -(float) dims[1] / 2.0f;
    affine[3][2] = 0.0f;
    field.setAffine(affine);
    return field;
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*from  ww  w . j av  a  2 s.c  o m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}