Search in sources :

Example 51 with IIOException

use of javax.imageio.IIOException in project imageio-ext by geosolutions-it.

the class NITFReader method readHeader.

public synchronized void readHeader() throws IOException {
    if (reader != null)
        return;
    if (handle == null) {
        throw new IllegalStateException("No input handle");
    }
    try {
        reader = new Reader();
        record = reader.read(handle);
    } catch (NITFException e) {
        LOGGER.severe(e.getLocalizedMessage());
        throw new IIOException("NITF Exception", e);
    }
}
Also used : NITFException(nitf.NITFException) ImageReader(javax.imageio.ImageReader) Reader(nitf.Reader) IIOException(javax.imageio.IIOException)

Example 52 with IIOException

use of javax.imageio.IIOException in project imageio-ext by geosolutions-it.

the class TIFFDecompressor method reformatData.

/**
 * Reformats data read as bytes into a short or int buffer.
 */
private static void reformatData(byte[] buf, int bytesPerRow, int numRows, short[] shortData, int[] intData, int outOffset, int outStride) throws IIOException {
    if (shortData != null) {
        if (DEBUG) {
            System.out.println("Reformatting data to short");
        }
        int inOffset = 0;
        int shortsPerRow = bytesPerRow / 2;
        int numExtraBytes = bytesPerRow % 2;
        for (int j = 0; j < numRows; j++) {
            int k = outOffset;
            for (int i = 0; i < shortsPerRow; i++) {
                shortData[k++] = (short) (((buf[inOffset++] & 0xff) << 8) | (buf[inOffset++] & 0xff));
            }
            if (numExtraBytes != 0) {
                shortData[k++] = (short) ((buf[inOffset++] & 0xff) << 8);
            }
            outOffset += outStride;
        }
    } else if (intData != null) {
        if (DEBUG) {
            System.out.println("Reformatting data to int");
        }
        int inOffset = 0;
        int intsPerRow = bytesPerRow / 4;
        int numExtraBytes = bytesPerRow % 4;
        for (int j = 0; j < numRows; j++) {
            int k = outOffset;
            for (int i = 0; i < intsPerRow; i++) {
                intData[k++] = ((buf[inOffset++] & 0xff) << 24) | ((buf[inOffset++] & 0xff) << 16) | ((buf[inOffset++] & 0xff) << 8) | (buf[inOffset++] & 0xff);
            }
            if (numExtraBytes != 0) {
                int shift = 24;
                int ival = 0;
                for (int b = 0; b < numExtraBytes; b++) {
                    ival |= (buf[inOffset++] & 0xff) << shift;
                    shift -= 8;
                }
                intData[k++] = ival;
            }
            outOffset += outStride;
        }
    } else {
        throw new IIOException("shortData == null && intData == null!");
    }
}
Also used : IIOException(javax.imageio.IIOException)

Example 53 with IIOException

use of javax.imageio.IIOException 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 54 with IIOException

use of javax.imageio.IIOException in project imageio-ext by geosolutions-it.

the class TIFFDeflateDecompressor method decodeRaw.

public synchronized void decodeRaw(byte[] b, int dstOffset, int bitsPerPixel, int scanlineStride) throws IOException {
    // Check bitsPerSample.
    if (predictor == BaselineTIFFTagSet.PREDICTOR_HORIZONTAL_DIFFERENCING) {
        int len = bitsPerSample.length;
        final int bps = bitsPerSample[0];
        if (bps != 8 && bps != 16) {
            throw new IIOException(bps + "-bit samples " + "are not supported for Horizontal " + "differencing Predictor");
        }
        for (int i = 0; i < len; i++) {
            if (bitsPerSample[i] != bps) {
                throw new IIOException("Varying sample width is not " + "supported for Horizontal " + "differencing Predictor (first: " + bps + ", unexpected:" + bitsPerSample[i] + ")");
            }
        }
    }
    // Seek to current tile data offset.
    stream.seek(offset);
    // Read the deflated data.
    byte[] srcData = new byte[byteCount];
    stream.readFully(srcData);
    int bytesPerRow = (srcWidth * bitsPerPixel + 7) / 8;
    byte[] buf;
    int bufOffset;
    if (bytesPerRow == scanlineStride) {
        buf = b;
        bufOffset = dstOffset;
    } else {
        buf = new byte[bytesPerRow * srcHeight];
        bufOffset = 0;
    }
    // Set the input to the Inflater.
    inflater.setInput(srcData);
    // Inflate the data.
    try {
        inflater.inflate(buf, bufOffset, bytesPerRow * srcHeight);
    } catch (DataFormatException dfe) {
        throw new IIOException(I18N.getString("TIFFDeflateDecompressor0"), dfe);
    }
    // Reset the Inflater.
    inflater.reset();
    if (predictor == BaselineTIFFTagSet.PREDICTOR_HORIZONTAL_DIFFERENCING) {
        if (bitsPerSample[0] == 8) {
            for (int j = 0; j < srcHeight; j++) {
                int count = bufOffset + samplesPerPixel * (j * srcWidth + 1);
                for (int i = samplesPerPixel; i < srcWidth * samplesPerPixel; i++) {
                    buf[count] += buf[count - samplesPerPixel];
                    count++;
                }
            }
        } else if (bitsPerSample[0] == 16) {
            if (stream.getByteOrder() == ByteOrder.LITTLE_ENDIAN) {
                for (int j = 0; j < srcHeight; j++) {
                    int count = dstOffset + samplesPerPixel * (j * srcWidth + 1) * 2;
                    for (int i = samplesPerPixel; i < srcWidth * samplesPerPixel; i++) {
                        int curr = (((int) buf[count]) & 0xFF) + (buf[count + 1] << 8);
                        int prev = (((int) buf[count - samplesPerPixel * 2]) & 0xFF) + (buf[count + 1 - samplesPerPixel * 2] << 8);
                        curr += prev;
                        buf[count] = (byte) curr;
                        buf[count + 1] = (byte) (curr >> 8);
                        count += 2;
                    }
                }
            } else {
                for (int j = 0; j < srcHeight; j++) {
                    int count = dstOffset + samplesPerPixel * (j * srcWidth + 1) * 2;
                    for (int i = samplesPerPixel; i < srcWidth * samplesPerPixel; i++) {
                        int curr = (((int) buf[count + 1]) & 0xFF) + (buf[count] << 8);
                        int prev = (((int) buf[count + 1 - samplesPerPixel * 2]) & 0xFF) + (buf[count - samplesPerPixel * 2] << 8);
                        curr += prev;
                        buf[count + 1] = (byte) curr;
                        buf[count] = (byte) (curr >> 8);
                        count += 2;
                    }
                }
            }
        } else
            throw new IIOException("Unexpected branch of Horizontal differencing Predictor, bps=" + bitsPerSample[0]);
    }
    if (bytesPerRow != scanlineStride) {
        if (DEBUG) {
            System.out.println("bytesPerRow != scanlineStride");
        }
        int off = 0;
        for (int y = 0; y < srcHeight; y++) {
            System.arraycopy(buf, off, b, dstOffset, bytesPerRow);
            off += bytesPerRow;
            dstOffset += scanlineStride;
        }
    }
}
Also used : DataFormatException(java.util.zip.DataFormatException) IIOException(javax.imageio.IIOException)

Example 55 with IIOException

use of javax.imageio.IIOException in project imageio-ext by geosolutions-it.

the class TIFFBaseJPEGCompressor method encode.

public final int encode(byte[] b, int off, int width, int height, int[] bitsPerSample, int scanlineStride) throws IOException {
    if (this.JPEGWriter == null) {
        throw new IIOException("JPEG writer has not been initialized!");
    }
    if (!((bitsPerSample.length == 3 && bitsPerSample[0] == 8 && bitsPerSample[1] == 8 && bitsPerSample[2] == 8) || (bitsPerSample.length == 1 && bitsPerSample[0] == 8))) {
        throw new IIOException("Can only JPEG compress 8- and 24-bit images!");
    }
    // Set the stream.
    ImageOutputStream ios;
    // usingCodecLib && !writeAbbreviatedStream
    long initialStreamPosition;
    if (usingCodecLib && !writeAbbreviatedStream) {
        ios = stream;
        initialStreamPosition = stream.getStreamPosition();
    } else {
        // is using a stream on the native side which cannot be reset.
        if (baos == null) {
            baos = new IIOByteArrayOutputStream();
        } else {
            baos.reset();
        }
        ios = new MemoryCacheImageOutputStream(baos);
        initialStreamPosition = 0L;
    }
    JPEGWriter.setOutput(ios);
    // Create a DataBuffer.
    DataBufferByte dbb;
    if (off == 0 || usingCodecLib) {
        dbb = new DataBufferByte(b, b.length);
    } else {
        // 
        // Workaround for bug in core Java Image I/O JPEG
        // ImageWriter which cannot handle non-zero offsets.
        // 
        int bytesPerSegment = scanlineStride * height;
        byte[] btmp = new byte[bytesPerSegment];
        System.arraycopy(b, off, btmp, 0, bytesPerSegment);
        dbb = new DataBufferByte(btmp, bytesPerSegment);
        off = 0;
    }
    // Set up the ColorSpace.
    int[] offsets;
    ColorSpace cs;
    if (bitsPerSample.length == 3) {
        offsets = new int[] { off, off + 1, off + 2 };
        cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    } else {
        offsets = new int[] { off };
        cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    }
    // Create the ColorModel.
    ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    // Create the SampleModel.
    SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitsPerSample.length, scanlineStride, offsets);
    // Create the WritableRaster.
    WritableRaster wras = Raster.createWritableRaster(sm, dbb, new Point(0, 0));
    // Create the BufferedImage.
    BufferedImage bi = new BufferedImage(cm, wras, false, null);
    // Get the pruned JPEG image metadata (may be null).
    IIOMetadata imageMetadata = getImageMetadata(writeAbbreviatedStream);
    // Compress the image into the output stream.
    int compDataLength;
    if (usingCodecLib && !writeAbbreviatedStream) {
        // Write complete JPEG stream
        JPEGWriter.write(null, new IIOImage(bi, null, imageMetadata), JPEGParam);
        compDataLength = (int) (stream.getStreamPosition() - initialStreamPosition);
    } else {
        if (writeAbbreviatedStream) {
            // Write abbreviated JPEG stream
            // First write the tables-only data.
            JPEGWriter.prepareWriteSequence(JPEGStreamMetadata);
            ios.flush();
            // Rewind to the beginning of the byte array.
            baos.reset();
            // Write the abbreviated image data.
            IIOImage image = new IIOImage(bi, null, imageMetadata);
            JPEGWriter.writeToSequence(image, JPEGParam);
            JPEGWriter.endWriteSequence();
        } else {
            // Write complete JPEG stream
            JPEGWriter.write(null, new IIOImage(bi, null, imageMetadata), JPEGParam);
        }
        compDataLength = baos.size();
        baos.writeTo(stream);
        baos.reset();
    }
    return compDataLength;
}
Also used : PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) ColorSpace(java.awt.color.ColorSpace) ComponentColorModel(java.awt.image.ComponentColorModel) IIOException(javax.imageio.IIOException) Point(java.awt.Point) DataBufferByte(java.awt.image.DataBufferByte) Point(java.awt.Point) BufferedImage(java.awt.image.BufferedImage) IIOImage(javax.imageio.IIOImage) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) SampleModel(java.awt.image.SampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) ComponentColorModel(java.awt.image.ComponentColorModel) ColorModel(java.awt.image.ColorModel) WritableRaster(java.awt.image.WritableRaster) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Aggregations

IIOException (javax.imageio.IIOException)60 Point (java.awt.Point)23 IOException (java.io.IOException)23 BufferedImage (java.awt.image.BufferedImage)12 Rectangle (java.awt.Rectangle)11 IndexColorModel (java.awt.image.IndexColorModel)7 SampleModel (java.awt.image.SampleModel)7 WritableRaster (java.awt.image.WritableRaster)7 Iterator (java.util.Iterator)7 ColorModel (java.awt.image.ColorModel)6 ArrayList (java.util.ArrayList)6 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)6 ImageInputStream (javax.imageio.stream.ImageInputStream)6 TIFFField (it.geosolutions.imageio.plugins.tiff.TIFFField)5 ColorSpace (java.awt.color.ColorSpace)5 ComponentSampleModel (java.awt.image.ComponentSampleModel)5 DataBufferByte (java.awt.image.DataBufferByte)5 ImageReader (javax.imageio.ImageReader)5 IIOMetadata (javax.imageio.metadata.IIOMetadata)5 ICC_ColorSpace (java.awt.color.ICC_ColorSpace)4