Example usage for java.awt.image WritableRaster getDataBuffer

List of usage examples for java.awt.image WritableRaster getDataBuffer

Introduction

In this page you can find the example usage for java.awt.image WritableRaster getDataBuffer.

Prototype

public DataBuffer getDataBuffer() 

Source Link

Document

Returns the DataBuffer associated with this Raster.

Usage

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

private static BufferedImage from1Bit(PDImage pdImage, WritableRaster raster) throws IOException {
    final PDColorSpace colorSpace = pdImage.getColorSpace();
    final int width = pdImage.getWidth();
    final int height = pdImage.getHeight();
    final float[] decode = getDecodeArray(pdImage);
    byte[] output = ((DataBufferByte) raster.getDataBuffer()).getData();

    // read bit stream
    InputStream iis = null;// ww w  . j  a  va2s.  com
    try {
        // create stream
        iis = pdImage.createInputStream();
        final boolean isIndexed = colorSpace instanceof PDIndexed;

        int rowLen = width / 8;
        if (width % 8 > 0) {
            rowLen++;
        }

        // read stream
        byte value0;
        byte value1;
        if (isIndexed || decode[0] < decode[1]) {
            value0 = 0;
            value1 = (byte) 255;
        } else {
            value0 = (byte) 255;
            value1 = 0;
        }
        byte[] buff = new byte[rowLen];
        int idx = 0;
        for (int y = 0; y < height; y++) {
            int x = 0;
            int readLen = iis.read(buff);
            for (int r = 0; r < rowLen && r < readLen; r++) {
                int value = buff[r];
                int mask = 128;
                for (int i = 0; i < 8; i++) {
                    int bit = value & mask;
                    mask >>= 1;
                    output[idx++] = bit == 0 ? value0 : value1;
                    x++;
                    if (x == width) {
                        break;
                    }
                }
            }
            if (readLen != rowLen) {
                LOG.warn("premature EOF, image will be incomplete");
                break;
            }
        }

        // use the color space to convert the image to RGB
        BufferedImage rgbImage = colorSpace.toRGBImage(raster);

        return rgbImage;
    } finally {
        if (iis != null) {
            iis.close();
        }
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

private static BufferedImage from8bit(PDImage pdImage, WritableRaster raster) throws IOException {
    InputStream input = pdImage.createInputStream();
    try {/*from w w w.  j  av a  2  s .c o  m*/
        // get the raster's underlying byte buffer
        byte[][] banks = ((DataBufferByte) raster.getDataBuffer()).getBankData();
        final int width = pdImage.getWidth();
        final int height = pdImage.getHeight();
        final int numComponents = pdImage.getColorSpace().getNumberOfComponents();
        int max = width * height;
        byte[] tempBytes = new byte[numComponents];
        for (int i = 0; i < max; i++) {
            input.read(tempBytes);
            for (int c = 0; c < numComponents; c++) {
                banks[c][i] = tempBytes[0 + c];
            }
        }
        // use the color space to convert the image to RGB
        return pdImage.getColorSpace().toRGBImage(raster);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDInlinedImage.java

/**
 * This will take the inlined image information and create a java.awt.Image from
 * it./*from w w w.java 2 s  .c  o  m*/
 * 
 * @param colorSpaces The ColorSpace dictionary from the current resources, if any.
 *
 * @return The image that this object represents.
 *
 * @throws IOException If there is an error creating the image.
 */
public BufferedImage createImage(Map colorSpaces) throws IOException {
    /*
     * This was the previous implementation, not sure which is better right now.
     *         byte[] transparentColors = new byte[]{(byte)0xFF,(byte)0xFF};
    byte[] colors=new byte[]{0, (byte)0xFF};
    IndexColorModel colorModel = new IndexColorModel( 1, 2, colors, colors, colors, transparentColors );
    BufferedImage image = new BufferedImage(
    params.getWidth(),
    params.getHeight(),
    BufferedImage.TYPE_BYTE_BINARY,
    colorModel );
    DataBufferByte buffer = new DataBufferByte( getImageData(), 1 );
    WritableRaster raster =
    Raster.createPackedRaster(
        buffer,
        params.getWidth(),
        params.getHeight(),
        params.getBitsPerComponent(),
        new Point(0,0) );
    image.setData( raster );
    return image;
     */

    //verify again pci32.pdf before changing below
    PDColorSpace pcs = params.getColorSpace(colorSpaces);
    ColorModel colorModel;
    if (pcs != null) {
        colorModel = pcs.createColorModel(params.getBitsPerComponent());
    } else {
        byte[] transparentColors = new byte[] { (byte) 0xFF, (byte) 0xFF };
        byte[] colors = new byte[] { 0, (byte) 0xFF };
        colorModel = new IndexColorModel(1, 2, colors, colors, colors, transparentColors);
    }

    boolean invert = false;
    // maybe a decode array is defined
    COSBase dictObj = params.getDictionary().getDictionaryObject(COSName.DECODE, COSName.D);
    if (dictObj != null && dictObj instanceof COSArray) {
        COSArray decode = (COSArray) dictObj;
        if (decode.getInt(0) == 1) {
            if (params.getBitsPerComponent() == 1) {
                // [1.0, 0.0] -> invert the "color" values
                invert = true;
            } else {
                //TODO implement decode array for BPC > 1
                LOG.warn("decode array is not implemented for BPC > 1");
            }
        }
    }

    List filters = params.getFilters();
    byte[] finalData;
    if (filters == null || filters.isEmpty()) {
        finalData = getImageData();
    } else {
        ByteArrayInputStream in = new ByteArrayInputStream(getImageData());
        ByteArrayOutputStream out = new ByteArrayOutputStream(getImageData().length);
        FilterManager filterManager = new FilterManager();
        for (int i = 0; i < filters.size(); i++) {
            out.reset();
            Filter filter = filterManager.getFilter((String) filters.get(i));
            filter.decode(in, out, params.getDictionary(), i);
            in = new ByteArrayInputStream(out.toByteArray());
        }
        finalData = out.toByteArray();
    }

    WritableRaster raster = colorModel.createCompatibleWritableRaster(params.getWidth(), params.getHeight());
    /*    Raster.createPackedRaster(
        buffer,
        params.getWidth(),
        params.getHeight(),
        params.getBitsPerComponent(),
        new Point(0,0) );
        */
    DataBuffer rasterBuffer = raster.getDataBuffer();
    if (rasterBuffer instanceof DataBufferByte) {
        DataBufferByte byteBuffer = (DataBufferByte) rasterBuffer;
        byte[] data = byteBuffer.getData();
        System.arraycopy(finalData, 0, data, 0, data.length);
        if (invert) {
            invertBitmap(data);
        }
    } else if (rasterBuffer instanceof DataBufferInt) {
        DataBufferInt byteBuffer = (DataBufferInt) rasterBuffer;
        int[] data = byteBuffer.getData();
        for (int i = 0; i < finalData.length; i++) {
            data[i] = (finalData[i] + 256) % 256;
            if (invert) {
                data[i] = (~data[i] & 0xFF);
            }
        }
    }
    BufferedImage image = new BufferedImage(colorModel, raster, false, null);
    image.setData(raster);
    return image;
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}//from ww w  .  j a  v  a  2s  .co  m
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}

From source file:org.apache.xmlgraphics.image.codec.png.PNGImageDecoder.java

/**
 * Reads in an image of a given size and returns it as a WritableRaster.
 *///w  w  w  .ja  va 2  s .  c o m
private void decodePass(final WritableRaster imRas, final int xOffset, final int yOffset, final int xStep,
        final int yStep, final int passWidth, final int passHeight) {
    if (passWidth == 0 || passHeight == 0) {
        return;
    }

    final int bytesPerRow = (this.inputBands * passWidth * this.bitDepth + 7) / 8;
    final int eltsPerRow = this.bitDepth == 16 ? bytesPerRow / 2 : bytesPerRow;
    byte[] curr = new byte[bytesPerRow];
    byte[] prior = new byte[bytesPerRow];

    // Create a 1-row tall Raster to hold the data
    final WritableRaster passRow = createRaster(passWidth, 1, this.inputBands, eltsPerRow, this.bitDepth);
    final DataBuffer dataBuffer = passRow.getDataBuffer();
    final int type = dataBuffer.getDataType();
    byte[] byteData = null;
    short[] shortData = null;
    if (type == DataBuffer.TYPE_BYTE) {
        byteData = ((DataBufferByte) dataBuffer).getData();
    } else {
        shortData = ((DataBufferUShort) dataBuffer).getData();
    }

    // Decode the (sub)image row-by-row
    int srcY, dstY;
    for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep) {
        // Read the filter type byte and a row of data
        int filter = 0;
        try {
            filter = this.dataStream.read();
            this.dataStream.readFully(curr, 0, bytesPerRow);
        } catch (final Exception e) {
            log.error("Exception", e);
        }

        switch (filter) {
        case PNG_FILTER_NONE:
            break;
        case PNG_FILTER_SUB:
            decodeSubFilter(curr, bytesPerRow, this.bytesPerPixel);
            break;
        case PNG_FILTER_UP:
            decodeUpFilter(curr, prior, bytesPerRow);
            break;
        case PNG_FILTER_AVERAGE:
            decodeAverageFilter(curr, prior, bytesPerRow, this.bytesPerPixel);
            break;
        case PNG_FILTER_PAETH:
            decodePaethFilter(curr, prior, bytesPerRow, this.bytesPerPixel);
            break;
        default:
            // Error -- uknown filter type
            final String msg = PropertyUtil.getString("PNGImageDecoder16");
            throw new RuntimeException(msg);
        }

        // Copy data into passRow byte by byte
        if (this.bitDepth < 16) {
            System.arraycopy(curr, 0, byteData, 0, bytesPerRow);
        } else {
            int idx = 0;
            for (int j = 0; j < eltsPerRow; j++) {
                shortData[j] = (short) (curr[idx] << 8 | curr[idx + 1] & 0xff);
                idx += 2;
            }
        }

        processPixels(this.postProcess, passRow, imRas, xOffset, xStep, dstY, passWidth);

        // Swap curr and prior
        final byte[] tmp = prior;
        prior = curr;
        curr = tmp;
    }
}

From source file:org.apache.xmlgraphics.image.codec.png.PNGRed.java

/**
 * Reads in an image of a given size and returns it as a WritableRaster.
 *///ww w .j a  va2s.  c om
private void decodePass(final WritableRaster imRas, final int xOffset, final int yOffset, final int xStep,
        final int yStep, final int passWidth, final int passHeight) {
    if (passWidth == 0 || passHeight == 0) {
        return;
    }

    final int bytesPerRow = (this.inputBands * passWidth * this.bitDepth + 7) / 8;
    final int eltsPerRow = this.bitDepth == 16 ? bytesPerRow / 2 : bytesPerRow;
    byte[] curr = new byte[bytesPerRow];
    byte[] prior = new byte[bytesPerRow];

    // Create a 1-row tall Raster to hold the data
    final WritableRaster passRow = createRaster(passWidth, 1, this.inputBands, eltsPerRow, this.bitDepth);
    final DataBuffer dataBuffer = passRow.getDataBuffer();
    final int type = dataBuffer.getDataType();
    byte[] byteData = null;
    short[] shortData = null;
    if (type == DataBuffer.TYPE_BYTE) {
        byteData = ((DataBufferByte) dataBuffer).getData();
    } else {
        shortData = ((DataBufferUShort) dataBuffer).getData();
    }

    // Decode the (sub)image row-by-row
    int srcY, dstY;
    for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep) {
        // Read the filter type byte and a row of data
        int filter = 0;
        try {
            filter = this.dataStream.read();
            this.dataStream.readFully(curr, 0, bytesPerRow);
        } catch (final Exception e) {
            log.error("Exception", e);
        }

        switch (filter) {
        case PNG_FILTER_NONE:
            break;
        case PNG_FILTER_SUB:
            decodeSubFilter(curr, bytesPerRow, this.bytesPerPixel);
            break;
        case PNG_FILTER_UP:
            decodeUpFilter(curr, prior, bytesPerRow);
            break;
        case PNG_FILTER_AVERAGE:
            decodeAverageFilter(curr, prior, bytesPerRow, this.bytesPerPixel);
            break;
        case PNG_FILTER_PAETH:
            decodePaethFilter(curr, prior, bytesPerRow, this.bytesPerPixel);
            break;
        default:
            // Error -- unknown filter type
            final String msg = PropertyUtil.getString("PNGImageDecoder16");
            throw new RuntimeException(msg);
        }

        // Copy data into passRow byte by byte
        if (this.bitDepth < 16) {
            System.arraycopy(curr, 0, byteData, 0, bytesPerRow);
        } else {
            int idx = 0;
            for (int j = 0; j < eltsPerRow; j++) {
                shortData[j] = (short) (curr[idx] << 8 | curr[idx + 1] & 0xff);
                idx += 2;
            }
        }

        processPixels(this.postProcess, passRow, imRas, xOffset, xStep, dstY, passWidth);

        // Swap curr and prior
        final byte[] tmp = prior;
        prior = curr;
        curr = tmp;
    }
}

From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java

private void computeRectIndirect(WritableRaster dest, Rectangle destRect) {
    try {/*  w ww.j  ava  2 s. com*/
        Path tile = decompressTile(tileIndex, getLevel());
        RenderedImage readTileImage = null;
        if (tile != null) {
            try (ImageReader imageReader = new ImageReader(tile)) {
                final DataBuffer dataBuffer = dest.getDataBuffer();
                int tileWidth = this.getTileWidth();
                int tileHeight = this.getTileHeight();
                final int fileTileX = destRect.x / tileLayout.tileWidth;
                final int fileTileY = destRect.y / tileLayout.tileHeight;
                int fileTileOriginX = destRect.x - fileTileX * tileLayout.tileWidth;
                int fileTileOriginY = destRect.y - fileTileY * tileLayout.tileHeight;
                Rectangle fileTileRect = tileDims.get(tile);
                if (fileTileRect == null) {
                    fileTileRect = new Rectangle(0, 0, imageReader.getImageWidth(),
                            imageReader.getImageHeight());
                    tileDims.put(tile, fileTileRect);
                }
                if (fileTileOriginX == 0 && tileLayout.tileWidth == tileWidth && fileTileOriginY == 0
                        && tileLayout.tileHeight == tileHeight
                        && tileWidth * tileHeight == dataBuffer.getSize()) {
                    readTileImage = imageReader.read();
                } else {
                    final Rectangle tileRect = new Rectangle(fileTileOriginX, fileTileOriginY, tileWidth,
                            tileHeight);
                    final Rectangle intersection = fileTileRect.intersection(tileRect);
                    if (!intersection.isEmpty()) {
                        readTileImage = imageReader.read(intersection);
                    }
                }
                if (readTileImage != null) {
                    Raster readBandRaster = readTileImage.getData().createChild(0, 0, readTileImage.getWidth(),
                            readTileImage.getHeight(), 0, 0, new int[] { bandIndex });
                    dest.setDataElements(dest.getMinX(), dest.getMinY(), readBandRaster);
                }
            } catch (IOException e) {
                logger.severe(e.getMessage());
            }
        }
    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java

private void computeRectDirect(WritableRaster dest, Rectangle destRect) {
    try (OpenJP2Decoder decoder = new OpenJP2Decoder(this.cacheDir, this.imageFile, this.bandIndex,
            this.dataType, getLevel(), 20, tileIndex)) {
        Raster readTileImage = null;
        final DataBuffer dataBuffer = dest.getDataBuffer();
        int tileWidth = this.getTileWidth();
        int tileHeight = this.getTileHeight();
        final int fileTileX = destRect.x / tileLayout.tileWidth;
        final int fileTileY = destRect.y / tileLayout.tileHeight;
        int fileTileOriginX = destRect.x - fileTileX * tileLayout.tileWidth;
        int fileTileOriginY = destRect.y - fileTileY * tileLayout.tileHeight;
        Dimension dimensions = decoder.getImageDimensions();
        Rectangle fileTileRect = new Rectangle(0, 0, dimensions.width, dimensions.height);

        if (fileTileOriginX == 0 && tileLayout.tileWidth == tileWidth && fileTileOriginY == 0
                && tileLayout.tileHeight == tileHeight && tileWidth * tileHeight == dataBuffer.getSize()) {
            readTileImage = decoder.read(null);
        } else {/*  www. j a v  a2  s  .  c o m*/
            final Rectangle tileRect = new Rectangle(fileTileOriginX, fileTileOriginY, tileWidth, tileHeight);
            final Rectangle intersection = fileTileRect.intersection(tileRect);
            if (!intersection.isEmpty()) {
                readTileImage = decoder.read(intersection);
            }
        }
        if (readTileImage != null) {
            Raster readBandRaster = readTileImage.createChild(0, 0, readTileImage.getWidth(),
                    readTileImage.getHeight(), 0, 0, bands);
            dest.setDataElements(dest.getMinX(), dest.getMinY(), readBandRaster);
        }

    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java

@Override
protected synchronized void computeRect(PlanarImage[] sources, WritableRaster dest, Rectangle destRect) {
    final DataBufferUShort dataBuffer = (DataBufferUShort) dest.getDataBuffer();
    final short[] tileData = dataBuffer.getData();

    final int tileWidth = this.getTileWidth();
    final int tileHeight = this.getTileHeight();
    final int tileX = destRect.x / tileWidth;
    final int tileY = destRect.y / tileHeight;

    if (tileWidth * tileHeight != tileData.length) {
        throw new IllegalStateException(
                String.format("tileWidth (=%d) * tileHeight (=%d) != tileData.length (=%d)", tileWidth,
                        tileHeight, tileData.length));
    }// www.  j  a v a  2 s.  co m

    final Dimension jp2TileDim = getDimAtResolutionLevel(tileLayout.tileWidth, tileLayout.tileHeight,
            getLevel());

    final int jp2TileWidth = jp2TileDim.width;
    final int jp2TileHeight = jp2TileDim.height;
    final int jp2TileX = destRect.x / jp2TileWidth;
    final int jp2TileY = destRect.y / jp2TileHeight;

    File outputFile = null;
    try {
        outputFile = new File(cacheDir, FileUtils.exchangeExtension(imageFile.getName(),
                String.format("_R%d_TX%d_TY%d.pgx", getLevel(), jp2TileX, jp2TileY)));
    } catch (Exception e) {
        logger.severe(Utils.getStackTrace(e));
    }

    final File outputFile0 = getFirstComponentOutputFile(outputFile);
    // todo - outputFile0 may have already been created, although 'opj_decompress' has not finished execution.
    //        This may be the reason for party filled tiles, that sometimes occur
    if (!outputFile0.exists()) {
        logger.finest(String.format("Jp2ExeImage.readTileData(): recomputing res=%d, tile=(%d,%d)\n",
                getLevel(), jp2TileX, jp2TileY));
        try {
            decompressTile(outputFile, jp2TileX, jp2TileY);
        } catch (IOException e) {
            logger.severe("opj_decompress process failed! :" + Utils.getStackTrace(e));
            if (outputFile0.exists() && !outputFile0.delete()) {
                logger.severe("Failed to delete file: " + outputFile0.getAbsolutePath());
            }
        }
        if (!outputFile0.exists()) {
            Arrays.fill(tileData, S2Config.FILL_CODE_NO_FILE);
            return;
        }
    }

    try {
        logger.finest(String.format("Jp2ExeImage.readTileData(): reading res=%d, tile=(%d,%d)\n", getLevel(),
                jp2TileX, jp2TileY));
        readTileData(outputFile0, tileX, tileY, tileWidth, tileHeight, jp2TileX, jp2TileY, jp2TileWidth,
                jp2TileHeight, tileData, destRect);
    } catch (IOException e) {
        logger.severe("Failed to read uncompressed file data: " + Utils.getStackTrace(e));
    }
}

From source file:org.jboss.test.selenium.ScreenshotInterceptor.java

public String calculateHash(BufferedImage image) {
    WritableRaster raster = image.getRaster();
    DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
    messageDigest.update(buffer.getData());
    return new BigInteger(1, messageDigest.digest()).toString(16);
}