Search in sources :

Example 6 with DataBufferDouble

use of java.awt.image.DataBufferDouble in project imageio-ext by geosolutions-it.

the class GDALImageReader method readDatasetRaster.

/**
 * Read data from the required region of the raster.
 *
 * @param destSM
 *                sample model for the image
 * @param dataset
 *                GDAL <code>Dataset</code> to read
 * @param srcRegion
 *                the source Region to be read
 * @param dstRegion
 *                the destination Region of the image read
 * @param selectedBands
 *                an array specifying the requested bands
 * @return the read <code>Raster</code>
 */
private Raster readDatasetRaster(SampleModel destSm, Dataset dataset, Rectangle srcRegion, Rectangle dstRegion, int[] selectedBands) throws IOException {
    SampleModel sampleModel = null;
    DataBuffer imgBuffer = null;
    Band pBand = null;
    try {
        int dstWidth = dstRegion.width;
        int dstHeight = dstRegion.height;
        int srcRegionXOffset = srcRegion.x;
        int srcRegionYOffset = srcRegion.y;
        int srcRegionWidth = srcRegion.width;
        int srcRegionHeight = srcRegion.height;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("SourceRegion = " + srcRegion.toString());
        // Getting number of bands
        final int nBands = selectedBands != null ? selectedBands.length : destSm.getNumBands();
        int[] banks = new int[nBands];
        int[] offsets = new int[nBands];
        // setting the number of pixels to read
        final int pixels = dstWidth * dstHeight;
        int bufferType = 0, bufferSize = 0;
        int typeSizeInBytes = 0;
        // ////////////////////////////////////////////////////////////////////
        // 
        // -------------------------------------------------------------------
        // Raster Creation >>> Step 2: Data Read
        // -------------------------------------------------------------------
        // 
        // ////////////////////////////////////////////////////////////////////
        // NOTE: Bands are not 0-base indexed, so we must add 1
        pBand = dataset.GetRasterBand(1);
        // setting buffer properties
        bufferType = pBand.getDataType();
        typeSizeInBytes = gdal.GetDataTypeSize(bufferType) / 8;
        bufferSize = nBands * pixels * typeSizeInBytes;
        // splitBands = false -> I read n Bands at once.
        // splitBands = false -> I need to read 1 Band at a time.
        boolean splitBands = false;
        if (bufferSize < 0 || destSm instanceof BandedSampleModel) {
            // The number resulting from the product
            // "numBands*pixels*gdal.GetDataTypeSize(buf_type) / 8"
            // may be negative (A very high number which is not
            // "int representable")
            // In such a case, we will read 1 band at a time.
            bufferSize = pixels * typeSizeInBytes;
            splitBands = true;
        }
        int dataBufferType = -1;
        byte[][] byteBands = new byte[nBands][];
        for (int k = 0; k < nBands; k++) {
            // I quit the loop
            if (k > 0 && !splitBands)
                break;
            final byte[] dataBuffer = new byte[bufferSize];
            final int returnVal;
            if (!splitBands) {
                // I can read nBands at once.
                final int[] bandsMap = new int[nBands];
                if (selectedBands != null) {
                    for (int i = 0; i < nBands; i++) bandsMap[i] = selectedBands[i] + 1;
                } else {
                    for (int i = 0; i < nBands; i++) bandsMap[i] = i + 1;
                }
                returnVal = dataset.ReadRaster(srcRegionXOffset, srcRegionYOffset, srcRegionWidth, srcRegionHeight, dstWidth, dstHeight, bufferType, dataBuffer, bandsMap, nBands * typeSizeInBytes, dstWidth * nBands * typeSizeInBytes, typeSizeInBytes);
                byteBands[k] = dataBuffer;
            } else {
                // I need to read 1 band at a time.
                Band rBand = null;
                try {
                    rBand = dataset.GetRasterBand(k + 1);
                    returnVal = rBand.ReadRaster(srcRegionXOffset, srcRegionYOffset, srcRegionWidth, srcRegionHeight, dstWidth, dstHeight, bufferType, dataBuffer);
                    byteBands[k] = dataBuffer;
                } finally {
                    if (rBand != null) {
                        try {
                            // Closing the band
                            rBand.delete();
                        } catch (Throwable e) {
                            if (LOGGER.isLoggable(Level.FINEST))
                                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
            if (returnVal == gdalconstConstants.CE_None) {
                if (!splitBands)
                    for (int band = 0; band < nBands; band++) {
                        banks[band] = band;
                        offsets[band] = band;
                    }
                else {
                    banks[k] = k;
                    offsets[k] = 0;
                }
            } else {
                // The read operation was not successfully computed.
                // Showing error messages.
                LOGGER.info(new StringBuilder("Last error: ").append(gdal.GetLastErrorMsg()).toString());
                LOGGER.info(new StringBuilder("Last error number: ").append(gdal.GetLastErrorNo()).toString());
                LOGGER.info(new StringBuilder("Last error type: ").append(gdal.GetLastErrorType()).toString());
                throw new RuntimeException(gdal.GetLastErrorMsg());
            }
        }
        // /////////////////////////////////////////////////////////////////////
        if (bufferType == gdalconstConstants.GDT_Byte) {
            if (!splitBands) {
                // final byte[] bytes = new byte[nBands * pixels];
                // bands[0].get(bytes, 0, nBands * pixels);
                imgBuffer = new DataBufferByte(byteBands[0], nBands * pixels);
            } else {
                // final byte[][] bytes = new byte[nBands][];
                // for (int i = 0; i < nBands; i++) {
                // //                    bytes[i] = new byte[pixels];
                // bands[i].get(bytes[i], 0, pixels);
                // }
                imgBuffer = new DataBufferByte(byteBands, pixels);
            }
            dataBufferType = DataBuffer.TYPE_BYTE;
        } else {
            ByteBuffer[] bands = new ByteBuffer[nBands];
            for (int k = 0; (splitBands && k < nBands) || (k < 1 && !splitBands); k++) {
                bands[k] = ByteBuffer.wrap(byteBands[k], 0, byteBands[k].length);
            }
            if (bufferType == gdalconstConstants.GDT_Int16 || bufferType == gdalconstConstants.GDT_UInt16) {
                if (!splitBands) {
                    // I get short values from the ByteBuffer using a view
                    // of the ByteBuffer as a ShortBuffer
                    // It is worth to create the view outside the loop.
                    short[] shorts = new short[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final ShortBuffer buff = bands[0].asShortBuffer();
                    buff.get(shorts, 0, nBands * pixels);
                    if (bufferType == gdalconstConstants.GDT_Int16)
                        imgBuffer = new DataBufferShort(shorts, nBands * pixels);
                    else
                        imgBuffer = new DataBufferUShort(shorts, nBands * pixels);
                } else {
                    short[][] shorts = new short[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        shorts[i] = new short[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asShortBuffer().get(shorts[i], 0, pixels);
                    }
                    if (bufferType == gdalconstConstants.GDT_Int16)
                        imgBuffer = new DataBufferShort(shorts, pixels);
                    else
                        imgBuffer = new DataBufferUShort(shorts, pixels);
                }
                if (bufferType == gdalconstConstants.GDT_UInt16)
                    dataBufferType = DataBuffer.TYPE_USHORT;
                else
                    dataBufferType = DataBuffer.TYPE_SHORT;
            } else if (bufferType == gdalconstConstants.GDT_Int32 || bufferType == gdalconstConstants.GDT_UInt32) {
                if (!splitBands) {
                    // I get int values from the ByteBuffer using a view
                    // of the ByteBuffer as an IntBuffer
                    // It is worth to create the view outside the loop.
                    int[] ints = new int[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final IntBuffer buff = bands[0].asIntBuffer();
                    buff.get(ints, 0, nBands * pixels);
                    imgBuffer = new DataBufferInt(ints, nBands * pixels);
                } else {
                    int[][] ints = new int[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        ints[i] = new int[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asIntBuffer().get(ints[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferInt(ints, pixels);
                }
                dataBufferType = DataBuffer.TYPE_INT;
            } else if (bufferType == gdalconstConstants.GDT_Float32) {
                if (!splitBands) {
                    // I get float values from the ByteBuffer using a view
                    // of the ByteBuffer as a FloatBuffer
                    // It is worth to create the view outside the loop.
                    float[] floats = new float[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final FloatBuffer buff = bands[0].asFloatBuffer();
                    buff.get(floats, 0, nBands * pixels);
                    imgBuffer = new DataBufferFloat(floats, nBands * pixels);
                } else {
                    float[][] floats = new float[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        floats[i] = new float[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asFloatBuffer().get(floats[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferFloat(floats, pixels);
                }
                dataBufferType = DataBuffer.TYPE_FLOAT;
            } else if (bufferType == gdalconstConstants.GDT_Float64) {
                if (!splitBands) {
                    // I get double values from the ByteBuffer using a view
                    // of the ByteBuffer as a DoubleBuffer
                    // It is worth to create the view outside the loop.
                    double[] doubles = new double[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final DoubleBuffer buff = bands[0].asDoubleBuffer();
                    buff.get(doubles, 0, nBands * pixels);
                    imgBuffer = new DataBufferDouble(doubles, nBands * pixels);
                } else {
                    double[][] doubles = new double[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        doubles[i] = new double[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asDoubleBuffer().get(doubles[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferDouble(doubles, pixels);
                }
                dataBufferType = DataBuffer.TYPE_DOUBLE;
            } else {
                // TODO: Handle more cases if needed. Show the name of the type
                // instead of the numeric value.
                LOGGER.info("The specified data type is actually unsupported: " + bufferType);
            }
        }
        // TODO: Fix this in compliance with the specified destSampleModel
        if (splitBands)
            sampleModel = new BandedSampleModel(dataBufferType, dstWidth, dstHeight, dstWidth, banks, offsets);
        else
            sampleModel = new PixelInterleavedSampleModel(dataBufferType, dstWidth, dstHeight, nBands, dstWidth * nBands, offsets);
    } finally {
        if (pBand != null) {
            try {
                // Closing the band
                pBand.delete();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        }
    }
    // dstRegion.x, dstRegion.y));
    return Raster.createWritableRaster(sampleModel, imgBuffer, null);
}
Also used : DataBufferDouble(java.awt.image.DataBufferDouble) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) Band(org.gdal.gdal.Band) FloatBuffer(java.nio.FloatBuffer) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) DataBufferShort(java.awt.image.DataBufferShort) BandedSampleModel(java.awt.image.BandedSampleModel) DataBufferUShort(java.awt.image.DataBufferUShort) DataBuffer(java.awt.image.DataBuffer) DoubleBuffer(java.nio.DoubleBuffer) ByteBuffer(java.nio.ByteBuffer) SampleModel(java.awt.image.SampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) IntBuffer(java.nio.IntBuffer) DataBufferFloat(java.awt.image.DataBufferFloat) ShortBuffer(java.nio.ShortBuffer)

Example 7 with DataBufferDouble

use of java.awt.image.DataBufferDouble in project imageio-ext by geosolutions-it.

the class TIFFDecompressor method decode.

/**
 * Decodes the input bit stream (located in the
 * <code>ImageInputStream</code> <code>stream</code>, at offset
 * <code>offset</code>, and continuing for <code>byteCount</code>
 * bytes) into the output <code>BufferedImage</code>
 * <code>image</code>.
 *
 * <p> The default implementation analyzes the destination image
 * to determine if it is suitable as the destination for the
 * <code>decodeRaw</code> method.  If not, a suitable image is
 * created.  Next, <code>decodeRaw</code> is called to perform the
 * actual decoding, and the results are copied into the
 * destination image if necessary.  Subsampling and offsetting are
 * performed automatically.
 *
 * <p> The precise responsibilities of this routine are as
 * follows.  The input bit stream is defined by the instance
 * variables <code>stream</code>, <code>offset</code>, and
 * <code>byteCount</code>.  These bits contain the data for the
 * region of the source image defined by <code>srcMinX</code>,
 * <code>srcMinY</code>, <code>srcWidth</code>, and
 * <code>srcHeight</code>.
 *
 * <p> The source data is required to be subsampling, starting at
 * the <code>sourceXOffset</code>th column and including
 * every <code>subsampleX</code>th pixel thereafter (and similarly
 * for <code>sourceYOffset</code> and
 * <code>subsampleY</code>).
 *
 * <p> Pixels are copied into the destination with an addition shift of
 * (<code>dstXOffset</code>, <code>dstYOffset</code>).  The complete
 * set of formulas relating the source and destination coordinate spaces
 * are:
 *
 * <pre>
 * dx = (sx - sourceXOffset)/subsampleX + dstXOffset;
 * dy = (sy - sourceYOffset)/subsampleY + dstYOffset;
 * </pre>
 *
 * Only source pixels such that <code>(sx - sourceXOffset) %
 * subsampleX == 0</code> and <code>(sy - sourceYOffset) %
 * subsampleY == 0</code> are copied.
 *
 * <p> The inverse mapping, from destination to source coordinates,
 * is one-to-one:
 *
 * <pre>
 * sx = (dx - dstXOffset)*subsampleX + sourceXOffset;
 * sy = (dy - dstYOffset)*subsampleY + sourceYOffset;
 * </pre>
 *
 * <p> The region of the destination image to be updated is given
 * by the instance variables <code>dstMinX</code>,
 * <code>dstMinY</code>, <code>dstWidth</code>, and
 * <code>dstHeight</code>.
 *
 * <p> It is possible that not all of the source data being read
 * will contribute to the destination image.  For example, the
 * destination offsets could be set such that some of the source
 * pixels land outside of the bounds of the image.  As a
 * convenience, the bounds of the active source region (that is,
 * the region of the strip or tile being read that actually
 * contributes to the destination image, taking clipping into
 * account) are available as <code>activeSrcMinX</code>,
 * <code>activeSrcMinY</code>, <code>activeSrcWidth</code> and
 * <code>activeSrcHeight</code>.  Thus, the source pixel at
 * (<code>activeSrcMinX</code>, <code>activeSrcMinY</code>) will
 * map to the destination pixel (<code>dstMinX</code>,
 * <code>dstMinY</code>).
 *
 * <p> The sequence of source bands given by
 * <code>sourceBands</code> are to be copied into the sequence of
 * bands in the destination given by
 * <code>destinationBands</code>.
 *
 * <p> Some standard tag information is provided the instance
 * variables <code>photometricInterpretation</code>,
 * <code>compression</code>, <code>samplesPerPixel</code>,
 * <code>bitsPerSample</code>, <code>sampleFormat</code>,
 * <code>extraSamples</code>, and <code>colorMap</code>.
 *
 * <p> In practice, unless there is a significant performance
 * advantage to be gained by overriding this routine, most users
 * will prefer to use the default implementation of this routine,
 * and instead override the <code>decodeRaw</code> and/or
 * <code>getRawImageType</code> methods.
 *
 * @exception IOException if an error occurs in
 * <code>decodeRaw</code>.
 */
public void decode() throws IOException {
    byte[] byteData = null;
    short[] shortData = null;
    int[] intData = null;
    float[] floatData = null;
    double[] doubleData = null;
    int dstOffset = 0;
    int pixelBitStride = 1;
    int scanlineStride = 0;
    if (useTurbo) {
        decodeRaw(byteData, dstOffset, pixelBitStride, scanlineStride);
    } else {
        // Analyze raw image
        this.rawImage = null;
        if (isImageSimple) {
            if (isBilevel) {
                rawImage = this.image;
            } else if (isContiguous) {
                rawImage = image.getSubimage(dstMinX, dstMinY, dstWidth, dstHeight);
            }
        }
        boolean isDirectCopy = rawImage != null;
        if (rawImage == null) {
            rawImage = createRawImage();
            if (rawImage == null) {
                throw new IIOException("Couldn't create image buffer!");
            }
        }
        WritableRaster ras = rawImage.getRaster();
        if (isBilevel) {
            Rectangle rect = isImageSimple ? new Rectangle(dstMinX, dstMinY, dstWidth, dstHeight) : ras.getBounds();
            byteData = ImageUtil.getPackedBinaryData(ras, rect);
            dstOffset = 0;
            pixelBitStride = 1;
            scanlineStride = (rect.width + 7) / 8;
        } else {
            SampleModel sm = ras.getSampleModel();
            DataBuffer db = ras.getDataBuffer();
            boolean isSupportedType = false;
            if (sm instanceof ComponentSampleModel) {
                ComponentSampleModel csm = (ComponentSampleModel) sm;
                dstOffset = csm.getOffset(-ras.getSampleModelTranslateX(), -ras.getSampleModelTranslateY());
                scanlineStride = csm.getScanlineStride();
                if (db instanceof DataBufferByte) {
                    DataBufferByte dbb = (DataBufferByte) db;
                    byteData = dbb.getData();
                    pixelBitStride = csm.getPixelStride() * 8;
                    isSupportedType = true;
                } else if (db instanceof DataBufferUShort) {
                    DataBufferUShort dbus = (DataBufferUShort) db;
                    shortData = dbus.getData();
                    pixelBitStride = csm.getPixelStride() * 16;
                    isSupportedType = true;
                } else if (db instanceof DataBufferShort) {
                    DataBufferShort dbs = (DataBufferShort) db;
                    shortData = dbs.getData();
                    pixelBitStride = csm.getPixelStride() * 16;
                    isSupportedType = true;
                } else if (db instanceof DataBufferInt) {
                    DataBufferInt dbi = (DataBufferInt) db;
                    intData = dbi.getData();
                    pixelBitStride = csm.getPixelStride() * 32;
                    isSupportedType = true;
                } else if (db instanceof DataBufferFloat) {
                    DataBufferFloat dbf = (DataBufferFloat) db;
                    floatData = dbf.getData();
                    pixelBitStride = csm.getPixelStride() * 32;
                    isSupportedType = true;
                } else if (db instanceof DataBufferDouble) {
                    DataBufferDouble dbf = (DataBufferDouble) db;
                    doubleData = dbf.getData();
                    pixelBitStride = csm.getPixelStride() * 64;
                    isSupportedType = true;
                }
            } else if (sm instanceof MultiPixelPackedSampleModel) {
                MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sm;
                dstOffset = mppsm.getOffset(-ras.getSampleModelTranslateX(), -ras.getSampleModelTranslateY());
                pixelBitStride = mppsm.getPixelBitStride();
                scanlineStride = mppsm.getScanlineStride();
                if (db instanceof DataBufferByte) {
                    DataBufferByte dbb = (DataBufferByte) db;
                    byteData = dbb.getData();
                    isSupportedType = true;
                } else if (db instanceof DataBufferUShort) {
                    DataBufferUShort dbus = (DataBufferUShort) db;
                    shortData = dbus.getData();
                    isSupportedType = true;
                } else if (db instanceof DataBufferInt) {
                    DataBufferInt dbi = (DataBufferInt) db;
                    intData = dbi.getData();
                    isSupportedType = true;
                }
            } else if (sm instanceof SinglePixelPackedSampleModel) {
                SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sm;
                dstOffset = sppsm.getOffset(-ras.getSampleModelTranslateX(), -ras.getSampleModelTranslateY());
                scanlineStride = sppsm.getScanlineStride();
                if (db instanceof DataBufferByte) {
                    DataBufferByte dbb = (DataBufferByte) db;
                    byteData = dbb.getData();
                    pixelBitStride = 8;
                    isSupportedType = true;
                } else if (db instanceof DataBufferUShort) {
                    DataBufferUShort dbus = (DataBufferUShort) db;
                    shortData = dbus.getData();
                    pixelBitStride = 16;
                    isSupportedType = true;
                } else if (db instanceof DataBufferInt) {
                    DataBufferInt dbi = (DataBufferInt) db;
                    intData = dbi.getData();
                    pixelBitStride = 32;
                    isSupportedType = true;
                }
            }
            if (!isSupportedType) {
                throw new IIOException("Unsupported raw image type: SampleModel = " + sm + "; DataBuffer = " + db);
            }
        }
        if (isBilevel) {
            // Bilevel data are always in a contiguous byte buffer.
            decodeRaw(byteData, dstOffset, pixelBitStride, scanlineStride);
        } else {
            SampleModel sm = ras.getSampleModel();
            // bits except at the end of a row.
            if (isDataBufferBitContiguous(sm)) {
                // Use byte or float data directly.
                if (byteData != null) {
                    if (DEBUG) {
                        System.out.println("Decoding bytes directly");
                    }
                    if (offset == 0 && byteCount == 0 && noData != null) {
                        setEmptyTile(byteData, dstOffset, pixelBitStride, scanlineStride, noData.byteValue());
                    } else {
                        decodeRaw(byteData, dstOffset, pixelBitStride, scanlineStride);
                    }
                } else if (floatData != null) {
                    if (DEBUG) {
                        System.out.println("Decoding floats directly");
                    }
                    if (offset == 0 && byteCount == 0 && noData != null) {
                        setEmptyTile(floatData, dstOffset, pixelBitStride, scanlineStride, noData.floatValue());
                    } else {
                        decodeRaw(floatData, dstOffset, pixelBitStride, scanlineStride);
                    }
                } else if (doubleData != null) {
                    if (DEBUG) {
                        System.out.println("Decoding doubles directly");
                    }
                    if (offset == 0 && byteCount == 0 && noData != null) {
                        setEmptyTile(doubleData, dstOffset, pixelBitStride, scanlineStride, noData.doubleValue());
                    } else {
                        decodeRaw(doubleData, dstOffset, pixelBitStride, scanlineStride);
                    }
                } else {
                    if (shortData != null) {
                        if (offset == 0 && byteCount == 0 && noData != null) {
                            setEmptyTile(shortData, dstOffset, pixelBitStride, scanlineStride, noData.shortValue());
                        } else if (areSampleSizesEqual(sm) && sm.getSampleSize(0) == 16) {
                            if (DEBUG) {
                                System.out.println("Decoding shorts directly");
                            }
                            // Decode directly into short data.
                            decodeRaw(shortData, dstOffset, pixelBitStride, scanlineStride);
                        } else {
                            if (DEBUG) {
                                System.out.println("Decoding bytes->shorts");
                            }
                            // Decode into bytes and reformat into shorts.
                            int bpp = getBitsPerPixel(sm);
                            int bytesPerRow = (bpp * srcWidth + 7) / 8;
                            byte[] buf = new byte[bytesPerRow * srcHeight];
                            decodeRaw(buf, 0, bpp, bytesPerRow);
                            reformatData(buf, bytesPerRow, srcHeight, shortData, null, dstOffset, scanlineStride);
                        }
                    } else if (intData != null) {
                        if (offset == 0 && byteCount == 0 && noData != null) {
                            setEmptyTile(intData, dstOffset, pixelBitStride, scanlineStride, noData.intValue());
                        } else if (areSampleSizesEqual(sm) && sm.getSampleSize(0) == 32) {
                            if (DEBUG) {
                                System.out.println("Decoding ints directly");
                            }
                            // Decode directly into int data.
                            decodeRaw(intData, dstOffset, pixelBitStride, scanlineStride);
                        } else {
                            if (DEBUG) {
                                System.out.println("Decoding bytes->ints");
                            }
                            // Decode into bytes and reformat into ints.
                            int bpp = getBitsPerPixel(sm);
                            int bytesPerRow = (bpp * srcWidth + 7) / 8;
                            byte[] buf = new byte[bytesPerRow * srcHeight];
                            decodeRaw(buf, 0, bpp, bytesPerRow);
                            reformatData(buf, bytesPerRow, srcHeight, null, intData, dstOffset, scanlineStride);
                        }
                    }
                }
            } else {
                if (DEBUG) {
                    System.out.println("Decoding discontiguous data");
                }
                // Read discontiguous data into bytes and set the samples
                // into the Raster.
                int bpp = getBitsPerPixel(sm);
                int bytesPerRow = (bpp * srcWidth + 7) / 8;
                byte[] buf = new byte[bytesPerRow * srcHeight];
                decodeRaw(buf, 0, bpp, bytesPerRow);
                reformatDiscontiguousData(buf, bytesPerRow, srcWidth, srcHeight, ras);
            }
        }
        if (colorConverter != null) {
            float[] rgb = new float[3];
            if (byteData != null) {
                for (int j = 0; j < dstHeight; j++) {
                    int idx = dstOffset;
                    for (int i = 0; i < dstWidth; i++) {
                        float x0 = (float) (byteData[idx] & 0xff);
                        float x1 = (float) (byteData[idx + 1] & 0xff);
                        float x2 = (float) (byteData[idx + 2] & 0xff);
                        colorConverter.toRGB(x0, x1, x2, rgb);
                        byteData[idx] = (byte) (rgb[0]);
                        byteData[idx + 1] = (byte) (rgb[1]);
                        byteData[idx + 2] = (byte) (rgb[2]);
                        idx += 3;
                    }
                    dstOffset += scanlineStride;
                }
            } else if (shortData != null) {
                if (sampleFormat[0] == BaselineTIFFTagSet.SAMPLE_FORMAT_SIGNED_INTEGER) {
                    for (int j = 0; j < dstHeight; j++) {
                        int idx = dstOffset;
                        for (int i = 0; i < dstWidth; i++) {
                            float x0 = (float) shortData[idx];
                            float x1 = (float) shortData[idx + 1];
                            float x2 = (float) shortData[idx + 2];
                            colorConverter.toRGB(x0, x1, x2, rgb);
                            shortData[idx] = (short) (rgb[0]);
                            shortData[idx + 1] = (short) (rgb[1]);
                            shortData[idx + 2] = (short) (rgb[2]);
                            idx += 3;
                        }
                        dstOffset += scanlineStride;
                    }
                } else {
                    for (int j = 0; j < dstHeight; j++) {
                        int idx = dstOffset;
                        for (int i = 0; i < dstWidth; i++) {
                            float x0 = (float) (shortData[idx] & 0xffff);
                            float x1 = (float) (shortData[idx + 1] & 0xffff);
                            float x2 = (float) (shortData[idx + 2] & 0xffff);
                            colorConverter.toRGB(x0, x1, x2, rgb);
                            shortData[idx] = (short) (rgb[0]);
                            shortData[idx + 1] = (short) (rgb[1]);
                            shortData[idx + 2] = (short) (rgb[2]);
                            idx += 3;
                        }
                        dstOffset += scanlineStride;
                    }
                }
            } else if (intData != null) {
                for (int j = 0; j < dstHeight; j++) {
                    int idx = dstOffset;
                    for (int i = 0; i < dstWidth; i++) {
                        float x0 = (float) intData[idx];
                        float x1 = (float) intData[idx + 1];
                        float x2 = (float) intData[idx + 2];
                        colorConverter.toRGB(x0, x1, x2, rgb);
                        intData[idx] = (int) (rgb[0]);
                        intData[idx + 1] = (int) (rgb[1]);
                        intData[idx + 2] = (int) (rgb[2]);
                        idx += 3;
                    }
                    dstOffset += scanlineStride;
                }
            } else if (floatData != null) {
                for (int j = 0; j < dstHeight; j++) {
                    int idx = dstOffset;
                    for (int i = 0; i < dstWidth; i++) {
                        float x0 = floatData[idx];
                        float x1 = floatData[idx + 1];
                        float x2 = floatData[idx + 2];
                        colorConverter.toRGB(x0, x1, x2, rgb);
                        floatData[idx] = rgb[0];
                        floatData[idx + 1] = rgb[1];
                        floatData[idx + 2] = rgb[2];
                        idx += 3;
                    }
                    dstOffset += scanlineStride;
                }
            }
        // int[] p = new int[3];
        // ras.getPixel(0, 0, p);
        // System.out.println("p00 = " +
        // p[0] + " " + p[1] + " " + p[2]);
        // ras.getPixel(1, 0, p);
        // System.out.println("p10 = " +
        // p[0] + " " + p[1] + " " + p[2]);
        // ras.getPixel(2, 0, p);
        // System.out.println("p20 = " +
        // p[0] + " " + p[1] + " " + p[2]);
        // ras.getPixel(3, 0, p);
        // System.out.println("p30 = " +
        // p[0] + " " + p[1] + " " + p[2]);
        // ColorSpace rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        // ColorConvertOp op = new ColorConvertOp(colorSpace, rgb, null);
        // WritableRaster dest = op.createCompatibleDestRaster(ras);
        // op.filter(ras, dest);
        // ras = dest;
        }
        if (photometricInterpretation == BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO) {
            if (byteData != null) {
                int bytesPerRow = (srcWidth * pixelBitStride + 7) / 8;
                for (int y = 0; y < srcHeight; y++) {
                    int offset = dstOffset + y * scanlineStride;
                    for (int i = 0; i < bytesPerRow; i++) {
                        byteData[offset + i] ^= 0xff;
                    }
                }
            } else if (shortData != null) {
                int shortsPerRow = (srcWidth * pixelBitStride + 15) / 16;
                if (sampleFormat[0] == BaselineTIFFTagSet.SAMPLE_FORMAT_SIGNED_INTEGER) {
                    for (int y = 0; y < srcHeight; y++) {
                        int offset = dstOffset + y * scanlineStride;
                        for (int i = 0; i < shortsPerRow; i++) {
                            int shortOffset = offset + i;
                            // XXX Does this make any sense?
                            shortData[shortOffset] = (short) (Short.MAX_VALUE - shortData[shortOffset]);
                        }
                    }
                } else {
                    for (int y = 0; y < srcHeight; y++) {
                        int offset = dstOffset + y * scanlineStride;
                        for (int i = 0; i < shortsPerRow; i++) {
                            shortData[offset + i] ^= 0xffff;
                        }
                    }
                }
            } else if (intData != null) {
                int intsPerRow = (srcWidth * pixelBitStride + 15) / 16;
                for (int y = 0; y < srcHeight; y++) {
                    int offset = dstOffset + y * scanlineStride;
                    for (int i = 0; i < intsPerRow; i++) {
                        int intOffset = offset + i;
                        // XXX Does this make any sense?
                        intData[intOffset] = Integer.MAX_VALUE - intData[intOffset];
                    }
                }
            } else if (floatData != null) {
                int floatsPerRow = (srcWidth * pixelBitStride + 15) / 16;
                for (int y = 0; y < srcHeight; y++) {
                    int offset = dstOffset + y * scanlineStride;
                    for (int i = 0; i < floatsPerRow; i++) {
                        int floatOffset = offset + i;
                        // XXX Does this make any sense?
                        floatData[floatOffset] = 1.0F - floatData[floatOffset];
                    }
                }
            }
        }
        if (isBilevel) {
            Rectangle rect = isImageSimple ? new Rectangle(dstMinX, dstMinY, dstWidth, dstHeight) : ras.getBounds();
            ImageUtil.setPackedBinaryData(byteData, ras, rect);
        }
        // equals the raster of 'image' or is a child thereof.
        if (isDirectCopy) {
            // rawImage == image) {
            return;
        }
    }
    // Copy the raw image data into the true destination image
    Raster src = rawImage.getRaster();
    // Create band child of source
    Raster srcChild = src.createChild(0, 0, srcWidth, srcHeight, srcMinX, srcMinY, planar ? null : sourceBands);
    WritableRaster dst = image.getRaster();
    // Create dst child covering area and bands to be written
    WritableRaster dstChild = dst.createWritableChild(dstMinX, dstMinY, dstWidth, dstHeight, dstMinX, dstMinY, destinationBands);
    if (subsampleX == 1 && subsampleY == 1 && !adjustBitDepths) {
        srcChild = srcChild.createChild(activeSrcMinX, activeSrcMinY, activeSrcWidth, activeSrcHeight, dstMinX, dstMinY, null);
        dstChild.setRect(srcChild);
    } else if (subsampleX == 1 && !adjustBitDepths) {
        int sy = activeSrcMinY;
        int dy = dstMinY;
        while (sy < srcMinY + srcHeight) {
            Raster srcRow = srcChild.createChild(activeSrcMinX, sy, activeSrcWidth, 1, dstMinX, dy, null);
            dstChild.setRect(srcRow);
            sy += subsampleY;
            ++dy;
        }
    } else {
        // /init vars
        int numBands = srcChild.getNumBands();
        int sy = activeSrcMinY;
        int dy = dstMinY;
        // get the databuffer type
        final int type = srcChild.getDataBuffer().getDataType();
        switch(type) {
            case DataBuffer.TYPE_BYTE:
            case DataBuffer.TYPE_INT:
            case DataBuffer.TYPE_SHORT:
            case DataBuffer.TYPE_USHORT:
                int[] p = srcChild.getPixel(srcMinX, srcMinY, (int[]) null);
                while (sy < activeSrcMinY + activeSrcHeight) {
                    int sx = activeSrcMinX;
                    int dx = dstMinX;
                    while (sx < activeSrcMinX + activeSrcWidth) {
                        srcChild.getPixel(sx, sy, p);
                        if (adjustBitDepths) {
                            for (int band = 0; band < numBands; band++) {
                                p[band] = bitDepthScale[band][p[band]];
                            }
                        }
                        dstChild.setPixel(dx, dy, p);
                        sx += subsampleX;
                        ++dx;
                    }
                    sy += subsampleY;
                    ++dy;
                }
                break;
            case DataBuffer.TYPE_DOUBLE:
                double[] d = srcChild.getPixel(srcMinX, srcMinY, (double[]) null);
                while (sy < activeSrcMinY + activeSrcHeight) {
                    int sx = activeSrcMinX;
                    int dx = dstMinX;
                    while (sx < activeSrcMinX + activeSrcWidth) {
                        srcChild.getPixel(sx, sy, d);
                        // if (adjustBitDepths) {
                        // for (int band = 0; band < numBands; band++) {
                        // d[band] = bitDepthScale[band][d[band]];
                        // }
                        // }
                        dstChild.setPixel(dx, dy, d);
                        sx += subsampleX;
                        ++dx;
                    }
                    sy += subsampleY;
                    ++dy;
                }
                break;
            case DataBuffer.TYPE_FLOAT:
                float[] f = srcChild.getPixel(srcMinX, srcMinY, (float[]) null);
                while (sy < activeSrcMinY + activeSrcHeight) {
                    int sx = activeSrcMinX;
                    int dx = dstMinX;
                    while (sx < activeSrcMinX + activeSrcWidth) {
                        srcChild.getPixel(sx, sy, f);
                        // if (adjustBitDepths) {
                        // for (int band = 0; band < numBands; band++) {
                        // d[band] = bitDepthScale[band][d[band]];
                        // }
                        // }
                        dstChild.setPixel(dx, dy, f);
                        sx += subsampleX;
                        ++dx;
                    }
                    sy += subsampleY;
                    ++dy;
                }
                break;
            default:
                break;
        }
    }
}
Also used : DataBufferDouble(java.awt.image.DataBufferDouble) Raster(java.awt.image.Raster) WritableRaster(java.awt.image.WritableRaster) Rectangle(java.awt.Rectangle) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) IIOException(javax.imageio.IIOException) ComponentSampleModel(java.awt.image.ComponentSampleModel) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) DataBufferShort(java.awt.image.DataBufferShort) ComponentSampleModel(java.awt.image.ComponentSampleModel) SampleModel(java.awt.image.SampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) WritableRaster(java.awt.image.WritableRaster) DataBufferFloat(java.awt.image.DataBufferFloat) DataBufferUShort(java.awt.image.DataBufferUShort) DataBuffer(java.awt.image.DataBuffer)

Example 8 with DataBufferDouble

use of java.awt.image.DataBufferDouble in project javacv by bytedeco.

the class Java2DFrameConverter method copy.

public static void copy(BufferedImage image, Frame frame, double gamma, boolean flipChannels, Rectangle roi) {
    Buffer out = frame.image[0].position(roi == null ? 0 : roi.y * frame.imageStride + roi.x * frame.imageChannels);
    SampleModel sm = image.getSampleModel();
    Raster r = image.getRaster();
    DataBuffer in = r.getDataBuffer();
    int x = -r.getSampleModelTranslateX();
    int y = -r.getSampleModelTranslateY();
    int step = sm.getWidth() * sm.getNumBands();
    int channels = sm.getNumBands();
    if (sm instanceof ComponentSampleModel) {
        step = ((ComponentSampleModel) sm).getScanlineStride();
        channels = ((ComponentSampleModel) sm).getPixelStride();
    } else if (sm instanceof SinglePixelPackedSampleModel) {
        step = ((SinglePixelPackedSampleModel) sm).getScanlineStride();
        channels = 1;
    } else if (sm instanceof MultiPixelPackedSampleModel) {
        step = ((MultiPixelPackedSampleModel) sm).getScanlineStride();
        // ??
        channels = ((MultiPixelPackedSampleModel) sm).getPixelBitStride() / 8;
    }
    int start = y * step + x * channels;
    if (in instanceof DataBufferByte) {
        byte[] a = ((DataBufferByte) in).getData();
        flipCopyWithGamma(ByteBuffer.wrap(a, start, a.length - start), step, (ByteBuffer) out, frame.imageStride, false, gamma, false, flipChannels ? channels : 0);
    } else if (in instanceof DataBufferDouble) {
        double[] a = ((DataBufferDouble) in).getData();
        flipCopyWithGamma(DoubleBuffer.wrap(a, start, a.length - start), step, (DoubleBuffer) out, frame.imageStride, gamma, false, flipChannels ? channels : 0);
    } else if (in instanceof DataBufferFloat) {
        float[] a = ((DataBufferFloat) in).getData();
        flipCopyWithGamma(FloatBuffer.wrap(a, start, a.length - start), step, (FloatBuffer) out, frame.imageStride, gamma, false, flipChannels ? channels : 0);
    } else if (in instanceof DataBufferInt) {
        int[] a = ((DataBufferInt) in).getData();
        int stride = frame.imageStride;
        if (out instanceof ByteBuffer) {
            out = ((ByteBuffer) out).order(flipChannels ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).asIntBuffer();
            stride /= 4;
        }
        flipCopyWithGamma(IntBuffer.wrap(a, start, a.length - start), step, (IntBuffer) out, stride, gamma, false, flipChannels ? channels : 0);
    } else if (in instanceof DataBufferShort) {
        short[] a = ((DataBufferShort) in).getData();
        flipCopyWithGamma(ShortBuffer.wrap(a, start, a.length - start), step, (ShortBuffer) out, frame.imageStride, true, gamma, false, flipChannels ? channels : 0);
    } else if (in instanceof DataBufferUShort) {
        short[] a = ((DataBufferUShort) in).getData();
        flipCopyWithGamma(ShortBuffer.wrap(a, start, a.length - start), step, (ShortBuffer) out, frame.imageStride, false, gamma, false, flipChannels ? channels : 0);
    } else {
        assert false;
    }
}
Also used : FloatBuffer(java.nio.FloatBuffer) ShortBuffer(java.nio.ShortBuffer) ByteBuffer(java.nio.ByteBuffer) IntBuffer(java.nio.IntBuffer) Buffer(java.nio.Buffer) DoubleBuffer(java.nio.DoubleBuffer) DataBuffer(java.awt.image.DataBuffer) DoubleBuffer(java.nio.DoubleBuffer) DataBufferDouble(java.awt.image.DataBufferDouble) Raster(java.awt.image.Raster) WritableRaster(java.awt.image.WritableRaster) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) ComponentSampleModel(java.awt.image.ComponentSampleModel) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) ByteBuffer(java.nio.ByteBuffer) DataBufferShort(java.awt.image.DataBufferShort) ComponentSampleModel(java.awt.image.ComponentSampleModel) SampleModel(java.awt.image.SampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) IntBuffer(java.nio.IntBuffer) DataBufferFloat(java.awt.image.DataBufferFloat) DataBufferUShort(java.awt.image.DataBufferUShort) ShortBuffer(java.nio.ShortBuffer) DataBuffer(java.awt.image.DataBuffer)

Aggregations

DataBufferDouble (java.awt.image.DataBufferDouble)8 DataBuffer (java.awt.image.DataBuffer)7 DataBufferByte (java.awt.image.DataBufferByte)6 DataBufferUShort (java.awt.image.DataBufferUShort)6 DataBufferFloat (java.awt.image.DataBufferFloat)5 DataBufferShort (java.awt.image.DataBufferShort)5 DataBufferInt (java.awt.image.DataBufferInt)4 PixelInterleavedSampleModel (java.awt.image.PixelInterleavedSampleModel)3 SampleModel (java.awt.image.SampleModel)3 ComponentSampleModel (java.awt.image.ComponentSampleModel)2 MultiPixelPackedSampleModel (java.awt.image.MultiPixelPackedSampleModel)2 Raster (java.awt.image.Raster)2 SinglePixelPackedSampleModel (java.awt.image.SinglePixelPackedSampleModel)2 WritableRaster (java.awt.image.WritableRaster)2 ByteBuffer (java.nio.ByteBuffer)2 DoubleBuffer (java.nio.DoubleBuffer)2 FloatBuffer (java.nio.FloatBuffer)2 IntBuffer (java.nio.IntBuffer)2 ShortBuffer (java.nio.ShortBuffer)2 Point (java.awt.Point)1