Search in sources :

Example 21 with IIOException

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

the class EmptyImage method locateIFD.

// Locate start of IFD for image.
// Throws IIOException if not at a TIFF header and
// IndexOutOfBoundsException if imageIndex is < -1 or is too big.
private void locateIFD(int imageIndex, long[] ifdpos, long[] ifd) throws IOException {
    if (imageIndex < -1) {
        throw new IndexOutOfBoundsException("imageIndex < -1!");
    }
    long startPos = stream.getStreamPosition();
    stream.seek(headerPosition);
    int byteOrder = stream.readUnsignedShort();
    if (byteOrder == 0x4d4d) {
        stream.setByteOrder(ByteOrder.BIG_ENDIAN);
    } else if (byteOrder == 0x4949) {
        stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
    } else {
        stream.seek(startPos);
        throw new IIOException("Illegal byte order");
    }
    final int magicNumber = stream.readUnsignedShort();
    if (magicNumber != 42 && magicNumber != 43) {
        stream.seek(startPos);
        throw new IIOException("Illegal magic number");
    }
    if (magicNumber == 43)
        isBtiff = true;
    if (!isBtiff) {
        ifdpos[0] = stream.getStreamPosition();
        ifd[0] = stream.readUnsignedInt();
        if (ifd[0] == 0) {
            // imageIndex has to be >= -1 due to check above.
            if (imageIndex > 0) {
                stream.seek(startPos);
                throw new IndexOutOfBoundsException("imageIndex is greater than the largest available index!");
            }
            return;
        }
        stream.seek(ifd[0]);
        for (int i = 0; imageIndex == -1 || i < imageIndex; i++) {
            int numFields;
            try {
                numFields = stream.readShort();
            } catch (EOFException eof) {
                stream.seek(startPos);
                ifd[0] = 0;
                return;
            }
            stream.skipBytes(12 * numFields);
            ifdpos[0] = stream.getStreamPosition();
            ifd[0] = stream.readUnsignedInt();
            if (ifd[0] == 0) {
                if (imageIndex != -1 && i < imageIndex - 1) {
                    stream.seek(startPos);
                    throw new IndexOutOfBoundsException("imageIndex is greater than the largest available index!");
                }
                break;
            }
            stream.seek(ifd[0]);
        }
    } else {
        short eight = stream.readShort();
        short zero = stream.readShort();
        ifdpos[0] = stream.getStreamPosition();
        ifd[0] = stream.readLong();
        if (ifd[0] == 0) {
            // imageIndex has to be >= -1 due to check above.
            if (imageIndex > 0) {
                stream.seek(startPos);
                throw new IndexOutOfBoundsException("imageIndex is greater than the largest available index!");
            }
            return;
        }
        stream.seek(ifd[0]);
        for (int i = 0; imageIndex == -1 || i < imageIndex; i++) {
            long numFields;
            try {
                numFields = stream.readLong();
            } catch (EOFException eof) {
                stream.seek(startPos);
                ifd[0] = 0;
                return;
            }
            stream.skipBytes(20 * numFields);
            ifdpos[0] = stream.getStreamPosition();
            ifd[0] = stream.readLong();
            if (ifd[0] == 0) {
                if (imageIndex != -1 && i < imageIndex - 1) {
                    stream.seek(startPos);
                    throw new IndexOutOfBoundsException("imageIndex is greater than the largest available index!");
                }
                break;
            }
            stream.seek(ifd[0]);
        }
    }
}
Also used : EOFException(java.io.EOFException) IIOException(javax.imageio.IIOException) Point(java.awt.Point)

Example 22 with IIOException

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

the class NITFReader method getImageReader.

private synchronized nitf.ImageReader getImageReader(int imageIndex) throws IOException {
    checkIndex(imageIndex);
    Integer key = new Integer(imageIndex);
    try {
        if (!imageReaderMap.containsKey(key))
            imageReaderMap.put(key, reader.getNewImageReader(imageIndex));
        return imageReaderMap.get(key);
    } catch (NITFException e) {
        LOGGER.severe(e.getLocalizedMessage());
        throw new IIOException("NITF Exception", e);
    }
}
Also used : NITFException(nitf.NITFException) IIOException(javax.imageio.IIOException)

Example 23 with IIOException

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

the class NITFReader method readRaster.

/**
 * Reads image data as bytes for the given region, and writes it to the given writable raster
 *
 * @param sourceRegion
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param destinationOffset
 * @param imRas
 * @return Raster
 * @throws IOException
 */
protected void readRaster(int imageIndex, Rectangle sourceRegion, Rectangle destRegion, int sourceXSubsampling, int sourceYSubsampling, int[] bandOffsets, int pixelSize, Point destinationOffset, WritableRaster imRas) throws IOException {
    checkIndex(imageIndex);
    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = subheader.getNumCols().getIntData();
        int numRows = subheader.getNumRows().getIntData();
        // image at once
        if ((destRegion.height * sourceYSubsampling) == numRows && (destRegion.width * sourceXSubsampling) == numCols) {
            readFullImage(imageIndex, destRegion, sourceXSubsampling, sourceYSubsampling, bandOffsets, pixelSize, imRas);
            return;
        } else // the general purpose case
        {
            int colBytes = destRegion.width * pixelSize;
            int dstMinX = imRas.getMinX();
            int dstMaxX = dstMinX + imRas.getWidth() - 1;
            int dstMinY = imRas.getMinY();
            int dstMaxY = dstMinY + imRas.getHeight() - 1;
            // int swap = 0;
            int nBands = subheader.getBandCount();
            /*
                 * NOTE: This is a "fix" that will be removed once the underlying NITRO library gets patched. Currently, if you make a request of a
                 * single band, it doesn't matter which band you request - the data from the first band will be returned regardless. This is obviously
                 * wrong. To thwart this, we will read all bands, then scale down what we return to the user based on their actual request.
                 */
            int[] requestBands = new int[nBands];
            for (int i = 0; i < nBands; ++i) requestBands[i] = i;
            byte[][] rowBuf = new byte[requestBands.length][colBytes];
            // make a SubWindow from the params
            // TODO may want to read by blocks or rows to make faster and
            // more
            // memory efficient
            SubWindow window;
            window = new SubWindow();
            window.setNumBands(requestBands.length);
            window.setBandList(requestBands);
            window.setNumCols(destRegion.width);
            window.setNumRows(1);
            window.setStartCol(sourceRegion.x);
            window.setStartRow(sourceRegion.y);
            // the NITRO library can do the subsampling for us
            if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
                DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
                window.setDownSampler(downSampler);
            }
            // String pixelJustification = record.getImages()[imageIndex]
            // .getSubheader().getPixelJustification().getStringData()
            // .trim();
            // swap = pixelJustification.equals("R") ? 1 : 0;
            List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();
            for (int i = 0; i < requestBands.length; ++i) {
                ByteBuffer bandBuf = null;
                bandBuf = ByteBuffer.wrap(rowBuf[i]);
                // bandBuf.order(ByteOrder.nativeOrder());
                // bandBuf.order(swap == 0 ? ByteOrder.BIG_ENDIAN
                // : ByteOrder.LITTLE_ENDIAN);
                bandBufs.add(bandBuf);
            }
            nitf.ImageReader imageReader = getImageReader(imageIndex);
            for (int srcY = 0; srcY < sourceRegion.height; srcY++) {
                if (sourceYSubsampling != 1 && (srcY % sourceYSubsampling) != 0)
                    continue;
                window.setStartRow(sourceRegion.y + srcY);
                // Read the row
                try {
                    imageReader.read(window, rowBuf);
                } catch (NITFException e) {
                    throw new IIOException("Error reading line " + srcY, e);
                }
                // Determine where the row will go in the destination
                int dstY = destinationOffset.y + srcY / sourceYSubsampling;
                if (dstY < dstMinY) {
                    // The row is above imRas
                    continue;
                }
                if (dstY > dstMaxY) {
                    // We're done with the image
                    break;
                }
                // Copy each (subsampled) source pixel into imRas
                for (int srcX = 0, dstX = destinationOffset.x; srcX < colBytes; srcX += pixelSize, dstX++) {
                    if (dstX < dstMinX) {
                        continue;
                    }
                    if (dstX > dstMaxX) {
                        break;
                    }
                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(bandOffsets[i]);
                        switch(pixelSize) {
                            case 1:
                                imRas.setSample(dstX, dstY, i, bandBuf.get(srcX));
                                break;
                            case 2:
                                imRas.setSample(dstX, dstY, i, bandBuf.getShort(srcX));
                                break;
                            case 4:
                                imRas.setSample(dstX, dstY, i, bandBuf.getFloat(srcX));
                                break;
                            case 8:
                                imRas.setSample(dstX, dstY, i, bandBuf.getDouble(srcX));
                                break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(e1);
    }
}
Also used : ArrayList(java.util.ArrayList) IIOException(javax.imageio.IIOException) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Point(java.awt.Point) DownSampler(nitf.DownSampler) PixelSkipDownSampler(nitf.PixelSkipDownSampler) ImageSubheader(nitf.ImageSubheader) NITFException(nitf.NITFException) PixelSkipDownSampler(nitf.PixelSkipDownSampler) SubWindow(nitf.SubWindow)

Example 24 with IIOException

use of javax.imageio.IIOException in project screenbird by adamhub.

the class Frame method getJPEGBounds.

/** @return the bounds of the image provided.
     * @throws UnsupportedOperationException if the file cannot be read
     * as an image by ImageIO classes.
     * @throws IOException if an error occurred while reading the file
     */
private static Dimension getJPEGBounds(File file) throws IOException, IIOException {
    FileInputStream in = null;
    try {
        //Hack for UNIX machines
        if (MediaUtil.osIsUnix())
            ImageIO.setUseCache(false);
        in = new FileInputStream(file);
        ImageIO.setCacheDirectory(new File(Settings.SCREEN_CAPTURE_DIR));
        ImageInputStream stream = ImageIO.createImageInputStream(in);
        Iterator iter = ImageIO.getImageReaders(stream);
        ImageReader reader = (ImageReader) iter.next();
        String formatName = reader.getFormatName().toLowerCase();
        if (formatName.indexOf("jpeg") == -1 && formatName.indexOf("jpg") == -1) {
            throw new IllegalArgumentException("This image file is not a JPEG image.  This encoder only supports JPEG images.");
        }
        if (reader == null) {
            throw new UnsupportedOperationException("The file \"" + file.getName() + "\" is not a supported image.");
        }
        reader.setInput(stream, false);
        int w = reader.getWidth(0);
        int h = reader.getHeight(0);
        reader.dispose();
        stream.close();
        return new Dimension(w, h);
    } catch (IllegalArgumentException e) {
        log(e);
    } catch (UnsupportedOperationException e) {
        log(e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
            log(e);
        }
    }
    return null;
}
Also used : ImageInputStream(javax.imageio.stream.ImageInputStream) Iterator(java.util.Iterator) Dimension(java.awt.Dimension) ImageReader(javax.imageio.ImageReader) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileInputStream(java.io.FileInputStream) IIOException(javax.imageio.IIOException) IOException(java.io.IOException)

Example 25 with IIOException

use of javax.imageio.IIOException in project jdk8u_jdk by JetBrains.

the class GIFImageReader method readMetadata.

// Stream must be positioned at start of metadata for 'currIndex'
private void readMetadata() throws IIOException {
    if (stream == null) {
        throw new IllegalStateException("Input not set!");
    }
    try {
        // Create an object to store the image metadata
        this.imageMetadata = new GIFImageMetadata();
        long startPosition = stream.getStreamPosition();
        while (true) {
            int blockType = stream.readUnsignedByte();
            if (blockType == 0x2c) {
                // Image Descriptor
                imageMetadata.imageLeftPosition = stream.readUnsignedShort();
                imageMetadata.imageTopPosition = stream.readUnsignedShort();
                imageMetadata.imageWidth = stream.readUnsignedShort();
                imageMetadata.imageHeight = stream.readUnsignedShort();
                int idPackedFields = stream.readUnsignedByte();
                boolean localColorTableFlag = (idPackedFields & 0x80) != 0;
                imageMetadata.interlaceFlag = (idPackedFields & 0x40) != 0;
                imageMetadata.sortFlag = (idPackedFields & 0x20) != 0;
                int numLCTEntries = 1 << ((idPackedFields & 0x7) + 1);
                if (localColorTableFlag) {
                    // Read color table if any
                    imageMetadata.localColorTable = new byte[3 * numLCTEntries];
                    stream.readFully(imageMetadata.localColorTable);
                } else {
                    imageMetadata.localColorTable = null;
                }
                // Record length of this metadata block
                this.imageMetadataLength = (int) (stream.getStreamPosition() - startPosition);
                // Now positioned at start of LZW-compressed pixels
                return;
            } else if (blockType == 0x21) {
                // Extension block
                int label = stream.readUnsignedByte();
                if (label == 0xf9) {
                    // Graphics Control Extension
                    // 4
                    int gceLength = stream.readUnsignedByte();
                    int gcePackedFields = stream.readUnsignedByte();
                    imageMetadata.disposalMethod = (gcePackedFields >> 2) & 0x3;
                    imageMetadata.userInputFlag = (gcePackedFields & 0x2) != 0;
                    imageMetadata.transparentColorFlag = (gcePackedFields & 0x1) != 0;
                    imageMetadata.delayTime = stream.readUnsignedShort();
                    imageMetadata.transparentColorIndex = stream.readUnsignedByte();
                    int terminator = stream.readUnsignedByte();
                } else if (label == 0x1) {
                    // Plain text extension
                    int length = stream.readUnsignedByte();
                    imageMetadata.hasPlainTextExtension = true;
                    imageMetadata.textGridLeft = stream.readUnsignedShort();
                    imageMetadata.textGridTop = stream.readUnsignedShort();
                    imageMetadata.textGridWidth = stream.readUnsignedShort();
                    imageMetadata.textGridHeight = stream.readUnsignedShort();
                    imageMetadata.characterCellWidth = stream.readUnsignedByte();
                    imageMetadata.characterCellHeight = stream.readUnsignedByte();
                    imageMetadata.textForegroundColor = stream.readUnsignedByte();
                    imageMetadata.textBackgroundColor = stream.readUnsignedByte();
                    imageMetadata.text = concatenateBlocks();
                } else if (label == 0xfe) {
                    // Comment extension
                    byte[] comment = concatenateBlocks();
                    if (imageMetadata.comments == null) {
                        imageMetadata.comments = new ArrayList();
                    }
                    imageMetadata.comments.add(comment);
                } else if (label == 0xff) {
                    // Application extension
                    int blockSize = stream.readUnsignedByte();
                    byte[] applicationID = new byte[8];
                    byte[] authCode = new byte[3];
                    // read available data
                    byte[] blockData = new byte[blockSize];
                    stream.readFully(blockData);
                    int offset = copyData(blockData, 0, applicationID);
                    offset = copyData(blockData, offset, authCode);
                    byte[] applicationData = concatenateBlocks();
                    if (offset < blockSize) {
                        int len = blockSize - offset;
                        byte[] data = new byte[len + applicationData.length];
                        System.arraycopy(blockData, offset, data, 0, len);
                        System.arraycopy(applicationData, 0, data, len, applicationData.length);
                        applicationData = data;
                    }
                    // Init lists if necessary
                    if (imageMetadata.applicationIDs == null) {
                        imageMetadata.applicationIDs = new ArrayList();
                        imageMetadata.authenticationCodes = new ArrayList();
                        imageMetadata.applicationData = new ArrayList();
                    }
                    imageMetadata.applicationIDs.add(applicationID);
                    imageMetadata.authenticationCodes.add(authCode);
                    imageMetadata.applicationData.add(applicationData);
                } else {
                    // Skip over unknown extension blocks
                    int length = 0;
                    do {
                        length = stream.readUnsignedByte();
                        stream.skipBytes(length);
                    } while (length > 0);
                }
            } else if (blockType == 0x3b) {
                // Trailer
                throw new IndexOutOfBoundsException("Attempt to read past end of image sequence!");
            } else {
                throw new IIOException("Unexpected block type " + blockType + "!");
            }
        }
    } catch (IIOException iioe) {
        throw iioe;
    } catch (IOException ioe) {
        throw new IIOException("I/O error reading image metadata!", ioe);
    }
}
Also used : ArrayList(java.util.ArrayList) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) IIOException(javax.imageio.IIOException) Point(java.awt.Point)

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