Java Code Examples for javax.imageio.ImageReader#getNumImages()

The following examples show how to use javax.imageio.ImageReader#getNumImages() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AwtRenderingBackend.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void drawImage(final ImageReader imageReader, final int dxI, final int dyI) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("[" + id_ + "] drawImage()");
    }

    if (imageReader.getNumImages(true) != 0) {
        final BufferedImage img = imageReader.read(0);

        final AffineTransform savedTransform = graphics2D_.getTransform();
        try {
            graphics2D_.setTransform(transformation_);
            graphics2D_.setColor(fillColor_);
            graphics2D_.drawImage(img, dxI, dyI, image_.getWidth(), image_.getHeight(), null);
        }
        finally {
            graphics2D_.setTransform(savedTransform);
        }
    }
}
 
Example 2
Source File: ImageLoadTwelveMonkeysTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
/**
 * Load a multi-page TIFF image and split it into its individual pages.
 */
@Test
public void testExtractPagesFromMultiPageTiffCompression4() throws Exception {

    File sourceImageFile = getImageFile("tiff", "test-multi-gray-compression-type-4.tiff");
    ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile);

    // get the first matching reader
    Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
    ImageReader imageReader = iterator.next();
    imageReader.setInput(is);

    // split the multi-page TIFF
    int pages = imageReader.getNumImages(true);
    for (int i = 0; i < pages; i++) {
        BufferedImage bufferedImage = imageReader.read(i);
        assertValidBufferedImage(bufferedImage);
    }

    assertEquals("Expect to have 2 pages", 2, pages);
}
 
Example 3
Source File: SourceImage.java    From screenstudio with GNU General Public License v3.0 6 votes vote down vote up
private BufferedImage[] readGif(File input) {
    BufferedImage[] images = new BufferedImage[0];
    try {
        ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
        ImageInputStream stream = ImageIO.createImageInputStream(input);
        reader.setInput(stream);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int index = 0; index < count; index++) {
            BufferedImage frame = reader.read(index);
            images[index] = new BufferedImage(mBounds.width, mBounds.height, mImageType);
            images[index].createGraphics().drawImage(frame.getScaledInstance(mBounds.width, mBounds.height, Image.SCALE_SMOOTH), 0, 0, null);
            data = ((DataBufferByte) images[index].getRaster().getDataBuffer()).getData();
        }
        mTimeDelay = 100;

    } catch (IOException ex) {

    }
    return images;
}
 
Example 4
Source File: AllowSearch.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void test(ImageReader reader, String format)
    throws IOException {
    File f = File.createTempFile("imageio", ".tmp");
    ImageInputStream stream = ImageIO.createImageInputStream(f);
    reader.setInput(stream, true);

    boolean gotISE = false;
    try {
        int numImages = reader.getNumImages(true);
    } catch (IOException ioe) {
        gotISE = false;
    } catch (IllegalStateException ise) {
        gotISE = true;
    }

    if (!gotISE) {
        throw new RuntimeException("Failed to get desired exception for " +
                                   format + " reader!");
    }
}
 
Example 5
Source File: ImageLoadJaiTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
/**
 * Load a multi-page TIFF image and split it into its individual pages.
 */
@Test
public void testExtractPagesFromMultiPageTiffCompression7() throws Exception {

    File sourceImageFile = getImageFile("tiff", "test-multi-rgb-compression-type-7.tiff");
    ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile);

    // get the first matching reader
    Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
    ImageReader imageReader = iterator.next();
    imageReader.setInput(is);

    // split the multi-page TIFF
    int pages = imageReader.getNumImages(true);
    for (int i = 0; i < pages; i++) {
        BufferedImage bufferedImage = imageReader.read(i);
        assertValidBufferedImage(bufferedImage);
    }

    assertEquals("Expect to have 10 pages", 10, pages);
}
 
Example 6
Source File: ImageLoadJaiTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
/**
 * Load a multi-page TIFF image and split it into its individual pages.
 */
@Test
public void testExtractPagesFromMultiPageTiffCompression4() throws Exception {

    File sourceImageFile = getImageFile("tiff", "test-multi-gray-compression-type-4.tiff");
    ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile);

    // get the first matching reader
    Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
    ImageReader imageReader = iterator.next();
    imageReader.setInput(is);

    // split the multi-page TIFF
    int pages = imageReader.getNumImages(true);
    for (int i = 0; i < pages; i++) {
        BufferedImage bufferedImage = imageReader.read(i);
        assertValidBufferedImage(bufferedImage);
    }

    assertEquals("Expect to have 2 pages", 2, pages);
}
 
Example 7
Source File: ImageLoadTwelveMonkeysTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
/**
 * Load a multi-page TIFF image and split it into its individual pages.
 */
@Test
public void testExtractPagesFromMultiPageTiffCompression7() throws Exception {

    File sourceImageFile = getImageFile("tiff", "test-multi-rgb-compression-type-7.tiff");
    ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile);

    // get the first matching reader
    Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
    ImageReader imageReader = iterator.next();
    imageReader.setInput(is);

    // split the multi-page TIFF
    int pages = imageReader.getNumImages(true);
    for (int i = 0; i < pages; i++) {
        BufferedImage bufferedImage = imageReader.read(i);
        assertValidBufferedImage(bufferedImage);
    }

    assertEquals("Expect to have 10 pages", 10, pages);
}
 
Example 8
Source File: GifFormat.java    From Azzet with Open Software License 3.0 5 votes vote down vote up
@Override
public BufferedImage[] loadAsset( InputStream input, AssetInfo assetInfo ) throws Exception
{
	// Get the image reader...
	Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix( "gif" );

	// Check that there is one (this should almost never fail).
	if (!iter.hasNext())
	{
		throw new RuntimeException( "gif image reader not found" );
	}

	// Take the GIF reader
	ImageReader image = iter.next();

	// Set the input stream to which to read the GIF from.
	image.setInput( ImageIO.createImageInputStream( input ) );

	// Calculate the number of frames in the GIF image.
	int imgs = image.getNumImages( true );

	// Read each frame from the GIF image.
	BufferedImage[] frames = new BufferedImage[imgs];

	for (int i = 0; i < imgs; i++)
	{
		frames[i] = image.read( i );
	}

	return frames;
}
 
Example 9
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 5 votes vote down vote up
/**
     * Gets a list of <code>IIOImage</code> objects for an image file.
     *
     * @param inputFile input image file. It can be any of the supported
     * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL
     * Ghostscript or PDFBox is installed
     * @return a list of <code>IIOImage</code> objects
     * @throws IOException
     */
    public static List<IIOImage> getIIOImageList(File inputFile) throws IOException {
        // convert to TIFF if PDF
        File imageFile = getImageFile(inputFile);

        List<IIOImage> iioImageList = new ArrayList<IIOImage>();
        String imageFormat = getImageFileFormat(imageFile);

        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
        if (!readers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
        }
        ImageReader reader = readers.next();

        try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) {
            reader.setInput(iis);

            int imageTotal = reader.getNumImages(true);

            for (int i = 0; i < imageTotal; i++) {
//                IIOImage oimage = new IIOImage(reader.read(i), null, reader.getImageMetadata(i));
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                iioImageList.add(oimage);
            }

            return iioImageList;
        } finally {
            if (reader != null) {
                reader.dispose();
            }

            // delete temporary TIFF image for PDF
            if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(TIFF_EXT)) {
                imageFile.delete();
            }
        }
    }
 
Example 10
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a list of <code>BufferedImage</code> objects for an image file.
 *
 * @param inputFile input image file. It can be any of the supported
 * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL
 * Ghostscript or PDFBox is installed
 * @return a list of <code>BufferedImage</code> objects
 * @throws IOException
 */
public static List<BufferedImage> getImageList(File inputFile) throws IOException {
    // convert to TIFF if PDF
    File imageFile = getImageFile(inputFile);

    List<BufferedImage> biList = new ArrayList<BufferedImage>();
    String imageFormat = getImageFileFormat(imageFile);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    if (!readers.hasNext()) {
        throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
    }
    ImageReader reader = readers.next();

    try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) {
        reader.setInput(iis);

        int imageTotal = reader.getNumImages(true);

        for (int i = 0; i < imageTotal; i++) {
            BufferedImage bi = reader.read(i);
            biList.add(bi);
        }

        return biList;
    } finally {
        if (reader != null) {
            reader.dispose();
        }

        // delete temporary TIFF image for PDF
        if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(TIFF_EXT)) {
            imageFile.delete();
        }
    }
}
 
Example 11
Source File: ImageUtils.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private static Image rescale(Image image, int width, int height) throws InvalidImageException {
    try {
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(image.getData());
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);

        while (imageReaders.hasNext()) {
            ImageReader reader = imageReaders.next();
            String discoveredType = reader.getFormatName();

            if (! ALLOWED_MIMETYPE.contains(discoveredType)) {
                throw new InvalidImageException(discoveredType + " format is not supported");
            }

            reader.setInput(imageInputStream);
            reader.getNumImages(true);
            BufferedImage bufferedImage = reader.read(0);
            java.awt.Image scaledImage = bufferedImage.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
            BufferedImage bufferedScaledImage = new BufferedImage(width, height, bufferedImage.getType());

            Graphics2D g2 = bufferedScaledImage.createGraphics();
            g2.drawImage(scaledImage, 0, 0, null);
            g2.dispose();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(bufferedScaledImage, discoveredType, bos);

            return new Image(image.getType(), image.getMimeType(), bos.toByteArray());
        }

        throw new InvalidImageException("Image can not be rescaled");
    } catch (IOException ioe) {
        throw new InvalidImageException("Image can not be rescaled", ioe);
    }
}
 
Example 12
Source File: AnimatedMessage.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public List<BufferedImage> getFrames(File input) {
    List<BufferedImage> images = new ArrayList<BufferedImage>();
    try {
        ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
        ImageInputStream in = ImageIO.createImageInputStream(input);
        reader.setInput(in);
        for (int i = 0, count = reader.getNumImages(true); i < count; i++) {
            BufferedImage image = reader.read(i); // read next frame from gif
            images.add(image);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return images;
}
 
Example 13
Source File: AnimationTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void checkAnimation() throws IOException {
    ImageReader r = ImageIO.getImageReadersByFormatName("GIF").next();
    r.setInput(ImageIO.createImageInputStream(new File(fname)));

    int n = r.getNumImages(true);
    for (int i = 0; i < n; i++) {
        BufferedImage f = r.read(i);
        checkFrame(i, f);
    }
    System.out.println("Test passed.");
}
 
Example 14
Source File: AnimationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void checkAnimation() throws IOException {
    ImageReader r = ImageIO.getImageReadersByFormatName("GIF").next();
    r.setInput(ImageIO.createImageInputStream(new File(fname)));

    int n = r.getNumImages(true);
    for (int i = 0; i < n; i++) {
        BufferedImage f = r.read(i);
        checkFrame(i, f);
    }
    System.out.println("Test passed.");
}
 
Example 15
Source File: Tesseract1.java    From tess4j with Apache License 2.0 4 votes vote down vote up
/**
 * Performs OCR operation.
 *
 * @param inputFile an image file
 * @param rect the bounding rectangle defines the region of the image to be
 * recognized. A rectangle of zero dimension or <code>null</code> indicates
 * the whole image.
 * @return the recognized text
 * @throws TesseractException
 */
@Override
public String doOCR(File inputFile, Rectangle rect) throws TesseractException {
    try {
        File imageFile = ImageIOHelper.getImageFile(inputFile);
        String imageFileFormat = ImageIOHelper.getImageFileFormat(imageFile);
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat);
        if (!readers.hasNext()) {
            throw new RuntimeException(ImageIOHelper.JAI_IMAGE_READER_MESSAGE);
        }
        ImageReader reader = readers.next();
        StringBuilder result = new StringBuilder();
        try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile);) {
            reader.setInput(iis);
            int imageTotal = reader.getNumImages(true);

            init();
            setTessVariables();

            for (int i = 0; i < imageTotal; i++) {
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                result.append(doOCR(oimage, inputFile.getPath(), rect, i + 1));
            }

            if (String.valueOf(TRUE).equals(prop.getProperty("tessedit_create_hocr"))) {
                result.insert(0, htmlBeginTag).append(htmlEndTag);
            }
        } finally {
            // delete temporary TIFF image for PDF
            if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(ImageIOHelper.TIFF_EXT)) {
                imageFile.delete();
            }
            reader.dispose();
            dispose();
        }

        return result.toString();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new TesseractException(e);
    }
}
 
Example 16
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a list of TIFF image files from an image file. It basically
 * converts images of other formats to TIFF format, or a multi-page TIFF
 * image to multiple TIFF image files.
 *
 * @param imageFile input image file
 * @param index an index of the page; -1 means all pages, as in a multi-page
 * TIFF image
 * @param preserve preserve compression mode
 * @return a list of TIFF image files
 * @throws IOException
 */
public static List<File> createTiffFiles(File imageFile, int index, boolean preserve) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    String imageFormat = getImageFileFormat(imageFile);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    if (!readers.hasNext()) {
        throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
    }
    ImageReader reader = readers.next();

    // Get tiff writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    if (!writers.hasNext()) {
        throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
    }
    ImageWriter writer = writers.next();

    try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) {
        reader.setInput(iis);
        // Read the stream metadata
        // IIOMetadata streamMetadata = reader.getStreamMetadata();

        // Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
        if (!preserve) {
            // not preserve original sizes; decompress
            tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);
        }
        // Read the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        int imageTotal = reader.getNumImages(true);

        for (int i = 0; i < imageTotal; i++) {
            // all if index == -1; otherwise, only index-th
            if (index == -1 || i == index) {
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
                try (ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile)) {
                    writer.setOutput(ios);
                    writer.write(streamMetadata, oimage, tiffWriteParam);
                    tiffFiles.add(tiffFile);
                }
            }
        }

        return tiffFiles;
    } finally {
        if (reader != null) {
            reader.dispose();
        }
        if (writer != null) {
            writer.dispose();
        }
    }
}
 
Example 17
Source File: Tesseract.java    From tess4j with Apache License 2.0 4 votes vote down vote up
/**
 * Performs OCR operation.
 *
 * @param inputFile an image file
 * @param rect the bounding rectangle defines the region of the image to be
 * recognized. A rectangle of zero dimension or <code>null</code> indicates
 * the whole image.
 * @return the recognized text
 * @throws TesseractException
 */
@Override
public String doOCR(File inputFile, Rectangle rect) throws TesseractException {
    try {
        File imageFile = ImageIOHelper.getImageFile(inputFile);
        String imageFileFormat = ImageIOHelper.getImageFileFormat(imageFile);
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat);
        if (!readers.hasNext()) {
            throw new RuntimeException(ImageIOHelper.JAI_IMAGE_READER_MESSAGE);
        }
        ImageReader reader = readers.next();
        StringBuilder result = new StringBuilder();
        try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile);) {
            reader.setInput(iis);
            int imageTotal = reader.getNumImages(true);

            init();
            setTessVariables();

            for (int i = 0; i < imageTotal; i++) {
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                result.append(doOCR(oimage, inputFile.getPath(), rect, i + 1));
            }

            if (String.valueOf(TRUE).equals(prop.getProperty("tessedit_create_hocr"))) {
                result.insert(0, htmlBeginTag).append(htmlEndTag);
            }
        } finally {
            // delete temporary TIFF image for PDF
            if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(ImageIOHelper.TIFF_EXT)) {
                imageFile.delete();
            }
            reader.dispose();
            dispose();
        }

        return result.toString();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new TesseractException(e);
    }
}
 
Example 18
Source File: AnimatedGifUtil.java    From ChatGameFontificator with The Unlicense 4 votes vote down vote up
/**
 * Fix (ditto) for Java's animated GIF interpretation
 * 
 * Adapted from http://stackoverflow.com/questions/26801433/fix-frame-rate-of-animated-gif-in-java#answer-26829534
 * 
 * @param url
 *            The URL for the animated GIF to be loaded
 * @param dim
 *            The dimension object to be filled by the width and height of the loaded animated GIF
 * @return The loaded animated GIF
 * @throws Exception
 */
public static Image loadDittoAnimatedGif(final URL url, Dimension dim)
{
    final Image dimImage = new ImageIcon(url).getImage();

    Image image = null;
    try
    {
        ImageReader gifReader = ImageIO.getImageReadersByFormatName(GIF_EXTENSION).next();
        InputStream imageStream = url.openStream();
        gifReader.setInput(ImageIO.createImageInputStream(imageStream));
        IIOMetadata imageMetaData = gifReader.getImageMetadata(0);
        String metaFormatName = imageMetaData.getNativeMetadataFormatName();
        final int frameCount = gifReader.getNumImages(true);

        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
        ImageWriter writer = ImageIO.getImageWriter(gifReader);
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);

        final int imgWidth = dimImage.getWidth(null);
        final int imgHeight = dimImage.getHeight(null);
        dim.setSize(imgWidth, imgHeight);

        for (int i = 0; i < frameCount; i++)
        {
            // This read method takes into account the frame's top and left coordinates
            BufferedImage frame = gifReader.read(i);
            IIOMetadataNode nodes = (IIOMetadataNode) gifReader.getImageMetadata(i).getAsTree(metaFormatName);

            for (int j = 0; j < nodes.getLength(); j++)
            {
                IIOMetadataNode node = (IIOMetadataNode) nodes.item(j);
                if (GRAPHIC_CTRL_EXT.equalsIgnoreCase(node.getNodeName()))
                {
                    int delay = Integer.parseInt(node.getAttribute(ATTRIBUTE_DELAY_TIME));
                    // Minimum delay for browsers, which delay animated GIFs much more than would be to spec
                    if (delay < MIN_ANI_GIF_DELAY)
                    {
                        node.setAttribute(ATTRIBUTE_DELAY_TIME, Integer.toString(MIN_ANI_GIF_DELAY));
                    }
                    // Java's interpretation of restore to previous doesn't seem to work correctly, 
                    // at least not for BTTV's (ditto)
                    if (node.getAttribute(ATTRIBUTE_DISPOSAL_METHOD).equals(DISPOSE_RESTORE_TO_PREVIOUS))
                    {
                        node.setAttribute(ATTRIBUTE_DISPOSAL_METHOD, DISPOSE_RESTORE_TO_BGCOLOR);
                    }
                }
            }

            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frame), null);
            metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodes);

            // This modified frame is necessary to get the correct image placement, width, and height in the final GIF
            BufferedImage frameMod = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics big = frameMod.getGraphics();
            big.drawImage(frame, 0, 0, null);

            IIOImage fixedFrame = new IIOImage(frameMod, null, metadata);
            writer.writeToSequence(fixedFrame, writer.getDefaultWriteParam());
        }
        writer.endWriteSequence();

        if (ios != null)
        {
            ios.close();
        }

        image = Toolkit.getDefaultToolkit().createImage(baoStream.toByteArray());
    }
    catch (Exception e)
    {
        // If anything goes wrong, just load it normally
        logger.error("Error loading animated GIF (ditto) from " + url, e);
        image = new ImageIcon(url).getImage();
        dim.setSize(image.getWidth(null), image.getHeight(null));
    }

    return image;
}
 
Example 19
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 4 votes vote down vote up
/**
     * Merges multiple images into one multi-page TIFF image.
     *
     * @param inputImages an array of image files
     * @param outputTiff the output multi-page TIFF file
     * @throws IOException
     */
    public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
        if (inputImages.length == 0) {
            // if no image
            return;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }
        ImageWriter writer = writers.next();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
//        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // commented out to preserve original sizes

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) {
            writer.setOutput(ios);
            boolean firstPage = true;
            int index = 1;
            for (File inputImage : inputImages) {
                String imageFileFormat = getImageFileFormat(inputImage);
                Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat);
                if (!readers.hasNext()) {
                    throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
                }
                ImageReader reader = readers.next();
                try (ImageInputStream iis = ImageIO.createImageInputStream(inputImage)) {
                    reader.setInput(iis);
                    int imageTotal = reader.getNumImages(true);
                    for (int i = 0; i < imageTotal; i++) {
                        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                        if (firstPage) {
                            writer.write(streamMetadata, oimage, tiffWriteParam);
                            firstPage = false;
                        } else {
                            writer.writeInsert(index++, oimage, tiffWriteParam);
                        }
                    }
                } finally {
                    if (reader != null) {
                        reader.dispose();
                    }
                }
            }
        } finally {
            writer.dispose();
        }
    }
 
Example 20
Source File: MockImageLoader.java    From dawnsci with Eclipse Public License 1.0 4 votes vote down vote up
private void readImages(IDataHolder output, ImageReader reader) throws IOException, ScanFileHolderException {
	int n = reader.getNumImages(true);

	if (n == 0) {
		return;
	}

	if (!loadData)
		return;

	boolean allSame = true;
	if (height < 0 || width < 0) {
		height = reader.getHeight(0); // this can throw NPE when using 12-bit reader
		width = reader.getWidth(0);
		for (int i = 1; i < n; i++) {
			if (height != reader.getHeight(i) || width != reader.getWidth(i)) {
				allSame = false;
				break;
			}
		}
	}

	final ImageTypeSpecifier its = reader.getRawImageType(0); // this raises an exception for 12-bit images when using standard reader
	if (allSame) {
		for (int i = 1; i < n; i++) {
			if (!its.equals(reader.getRawImageType(i))) {
				throw new ScanFileHolderException("Type of image in stack does not match first");
			}
		}
	}
	int dtype = AWTImageUtils.getDTypeFromImage(its.getSampleModel(), keepBitWidth)[0];
	if (n == 1) {
		ILazyDataset image;
		if (loadLazily) {
			image = createLazyDataset(dtype, height, width);
		} else {
			image = createDataset(reader.read(0));
		}
		image.setName(DEF_IMAGE_NAME);
		image.setMetadata(metadata);
		output.addDataset(DEF_IMAGE_NAME, image);
	} else if (allSame) {
		ILazyDataset ld = createLazyDataset(dtype, n, height, width);
		ld.setMetadata(metadata);
		output.addDataset(STACK_NAME, ld);
	} else {
		createLazyDatasets(output, reader);
	}

	if (loadMetadata) {
		createMetadata(output, reader);
		metadata.setMetadata(metadataMap);
		output.setMetadata(metadata);
	}
}