Example usage for javax.imageio ImageReader setInput

List of usage examples for javax.imageio ImageReader setInput

Introduction

In this page you can find the example usage for javax.imageio ImageReader setInput.

Prototype

public void setInput(Object input) 

Source Link

Document

Sets the input source to use to the given ImageInputStream or other Object .

Usage

From source file:org.uiautomation.ios.server.servlet.ResourceServlet.java

private boolean validImage(File f) throws IOException {
    InputStream is = new FileInputStream(f);
    try {//from  w  w  w  .ja  v  a 2  s  .  co  m
        //is = new FileInputStream(f);

        final ImageInputStream imageInputStream = ImageIO.createImageInputStream(is);
        final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
        if (!imageReaders.hasNext()) {
            // not an image
            return false;
        }
        final ImageReader imageReader = imageReaders.next();
        imageReader.setInput(imageInputStream);
        final BufferedImage image = imageReader.read(0);
        if (image == null) {
            // empty
            return false;
        }
        image.flush();
        return true;
    } catch (final IndexOutOfBoundsException e) {
        // truncated
        return false;
    } catch (final IIOException e) {
        if (e.getCause() instanceof EOFException) {
            // truncated
            return false;
        }
    } catch (Exception e) {
        return false;
    } finally {
        is.close();
    }
    return true;
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * Convert multipage TIFF to single page TIFF.
 * @param srcFiles Array of source files to convert.
 * @param destPath Folder to store single page TIFFs in.
 * @param archivePath Path to move source TIFF files to after single page TIFFs created.
 * @param pattern Pattern of single page TIFF file names.  Java NumberFormatter used with page number to create file name.
 * @param multipage Set to true if source TIFFs should be coverted to multi-page TIFF.
 * @param dpi DPI to set TIFFs to.//from ww w  .ja v  a  2 s.  c  om
 * @return Returns a list of files in destination path.
 * @throws net.filterlogic.util.imaging.OpenCaptureImagingException
 */
public static List toTIFF(String[] srcFiles, String destPath, String archivePath, String pattern,
        boolean multipage, int dpi) throws OpenCaptureImagingException {
    String pathSep = System.getProperty("file.separator");
    boolean jaiSupport = true;

    int pageCount = 0;
    int fileNameCount = 0;

    byte[] imageData = null;

    // make sure destpath has trailing slash.
    if (destPath.lastIndexOf(pathSep) != destPath.length() - 1)
        destPath += pathSep;

    // create path if doesn't exist
    if (!Path.ValidatePath(destPath))
        if (!Path.createPath(destPath))
            throw new OpenCaptureImagingException(
                    "Unable to create destination path for imported images [" + destPath + "]");

    // make sure archivePath has trailing slash
    if (archivePath.lastIndexOf(pathSep) != archivePath.length() - 1)
        archivePath += pathSep;

    if (!Path.ValidatePath(archivePath))
        if (!Path.createPath(archivePath))
            throw new OpenCaptureImagingException(
                    "Unable to create archive path for imported images [" + archivePath + "]");

    // set a default pattern if one not passed.
    if (pattern.trim().length() < 1)
        pattern = "#";

    NumberFormat formatter = new DecimalFormat(pattern);

    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < srcFiles.length; i++) {
        try {

            File f = new File(srcFiles[i]);
            imageData = null;

            ImageIO.setUseCache(false);
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
            java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);

            ImageReader reader1 = null;

            if (readers.hasNext()) {
                reader1 = (ImageReader) readers.next();
                jaiSupport = true;
            } else
                jaiSupport = false;

            if (jaiSupport) {
                //ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
                reader1.setInput(imageInputStream);

                pageCount = reader1.getNumImages(true);
            } else {
                String newFileName = bigEndian2LittleEndian(f.getAbsolutePath());

                if (imageInputStream != null) {
                    imageInputStream.flush();
                    imageInputStream.close();

                    reader1.setInput(imageInputStream);
                    pageCount = reader1.getNumImages(true);

                }

                imageInputStream = ImageIO.createImageInputStream(new File(newFileName));

                readers = ImageIO.getImageReaders(imageInputStream);

            }
            //                Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
            //                ImageWriter writer = (ImageWriter)writers.next();

            //ImageWriteParam param = writer.getDefaultWriteParam();

            //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            //String[] legalTypes = param.getCompressionTypes();

            //param.setCompressionType("PackBits");

            //ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ImageOutputStream ios = null;
            BufferedImage img = null;

            // break out each page to single file
            for (int t = 0; t < pageCount; t++) {

                // format filenumber
                String tifName = destPath + formatter.format(fileNameCount) + ".tif";

                while (new File(tifName).exists()) {
                    tifName = destPath + formatter.format(++fileNameCount) + ".tif";
                }

                FileOutputStream file = new FileOutputStream(new File(tifName));

                if (jaiSupport) {
                    img = reader1.read(t);
                    IIOImage iioimg = reader1.readAll(t, null);
                    //ios = ImageIO.createImageOutputStream(file);
                    //IIOMetadata iiom = getMetadata(writer, img, null, 200);
                } else {
                    img = loadTIFF(imageData, t);
                }
                TIFFEncodeParam tep = setEncoder(TIFFEncodeParam.COMPRESSION_PACKBITS, 200);

                ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", file, tep);

                encoder.encode(img);
                //boolean ok = ImageIO.write(img, "tiff", ios);
                //writer.setOutput(ios);
                //writer.write(iiom, iioimg, null);

                img.flush();

                //ios.flush();
                //ios.close();
                // ios = null;
                //iioimg = null;
                //iiom = null;
                img = null;
                //writer.dispose();
                //byteOut.flush();
                file.close();

                file = null;

                //System.out.println("Add file!");

                list.add(tifName);
            }

            if (jaiSupport) {
                reader1.dispose();
            }

            readers = null;

            //                writer.dispose();
            //                writers = null;

            imageInputStream.flush();
            imageInputStream.close();
            imageInputStream = null;

            f = null;

            // move file with overwrite
            if (!net.filterlogic.io.FileAccess.Move(srcFiles[i], archivePath, true))
                throw new Exception("Unable to move input file to archive path [" + srcFiles[i] + "] to ["
                        + archivePath + "]");

        } catch (Exception e) {
            throw new OpenCaptureImagingException(e.toString());
        }
    }

    return list;
}

From source file:org.geoserver.wps.ppio.CoveragePPIOTest.java

private void testIsFormat(GridCoverage2D coverage, CoveragePPIO ppio, File encodedFile, String formatName)
        throws Exception {
    try (FileOutputStream fos = new FileOutputStream(encodedFile)) {
        ppio.encode(coverage, fos);//w  w w .j  av  a2 s  . co  m
    }
    try (FileImageInputStream fis = new FileImageInputStream(encodedFile)) {
        ImageReader imageReader = null;
        try {
            imageReader = ImageIO.getImageReaders(fis).next();
            imageReader.setInput(fis);
            assertTrue(formatName.equalsIgnoreCase(imageReader.getFormatName()));
            assertNotNull(imageReader.read(0));
        } finally {
            if (imageReader != null) {
                try {
                    imageReader.dispose();
                } catch (Throwable t) {
                    // Ignore it.
                }
            }
        }
    }
}

From source file:ImageIOTest.java

/**
 * Open a file and load the images./*w w  w. j  a v a 2s  .c  o  m*/
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}

From source file:net.algart.simagis.imageio.IIOMetadataToJsonConverter.java

private JSONObject extendedReadExif(InputStream inputStream) throws IOException, JSONException {
    assert inputStream != null;
    ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
    Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
    try {/* w  w  w .j  av  a2  s. com*/
        if (!readers.hasNext()) {
            return null; // no readers to read such "Exif"
        }
        ImageReader reader = readers.next();
        try {
            reader.setInput(iis);
            return toJson(reader.getImageMetadata(0));
        } finally {
            reader.dispose();
        }
    } finally {
        iis.close();
    }
}

From source file:com.qwazr.extractor.parser.ImageParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final Path path,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {

    final ImagePHash imgPhash = new ImagePHash();
    try (final ImageInputStream in = ImageIO.createImageInputStream(path.toFile())) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ParserFieldsBuilder result = resultBuilder.newDocument();
            ImageReader reader = readers.next();
            resultBuilder.metas().set(MIME_TYPE, "image/" + reader.getFormatName().toLowerCase());
            try {
                reader.setInput(in);
                result.add(WIDTH, reader.getWidth(0));
                result.add(HEIGHT, reader.getHeight(0));
                result.add(FORMAT, reader.getFormatName());
                result.add(PHASH, imgPhash.getHash(reader.read(0)));
                IIOMetadata metadata = reader.getImageMetadata(0);
                if (metadata != null) {
                    String[] names = metadata.getMetadataFormatNames();
                    if (names != null)
                        for (String name : names)
                            browseNodes("META", metadata.getAsTree(name), result);
                }//from   w  ww .ja va  2  s .co m
            } finally {
                reader.dispose();
            }
        }
    }
}

From source file:uk.bl.wa.analyser.payload.ImageAnalyser.java

@Override
public void analyse(String source, ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) {
    // Set up metadata object to pass to parsers:
    Metadata metadata = new Metadata();
    // Skip large images:
    if (header.getLength() > max_size_bytes) {
        return;// w ww.jav a2s  .  c  om
    }

    // Only attempt to analyse a random sub-set of the data:
    // (prefixing with static test of a final value to allow JIT to fully
    // optimise out the "OR Math.random()" bit)
    if (sampleRate >= 1.0 || Math.random() < sampleRate) {
        // Increment number of images sampled:
        sampleCount++;

        // images are enabled, we still want to extract image/height (fast)
        //This method takes 0.2ms for a large image. I can be done even faster if needed(but more complicated)).
        //see https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java

        ImageInputStream input = null;
        ImageReader reader = null;
        try {
            input = ImageIO.createImageInputStream(tikainput);
            reader = ImageIO.getImageReaders(input).next();
            reader.setInput(input);
            // Get dimensions of first image in the stream, without decoding pixel values
            int width = reader.getWidth(0);
            int height = reader.getHeight(0);

            // Store basic image data:
            solr.addField(SolrFields.IMAGE_HEIGHT, "" + height);
            solr.addField(SolrFields.IMAGE_WIDTH, "" + width);
            solr.addField(SolrFields.IMAGE_SIZE, "" + (height * width));
        } catch (Exception e) {
            //it is known that (most) .ico and (all) .svg are not supported by java. Do not log, since it will spam.
            // log.warn("Unable to extract image height/width/size for url:"+header.getUrl(),e);

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

    }
}

From source file:org.olat.core.commons.services.image.spi.AbstractImageHelper.java

private Size getImageSize(VFSLeaf media, String suffix) {
    Size result = null;//from   w  w w  .  jav a 2 s  .  c o  m
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageInputStream stream = null;
        InputStream mediaStream = null;
        ImageReader reader = iter.next();
        try {
            mediaStream = media.getInputStream();
            if (mediaStream != null) {
                stream = new MemoryCacheImageInputStream(mediaStream);
                reader.setInput(stream);
                int readerMinIndex = reader.getMinIndex();
                int width = reader.getWidth(readerMinIndex);
                int height = reader.getHeight(readerMinIndex);
                result = new Size(width, height, 0, 0, false);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            IOUtils.closeQuietly(stream);
            IOUtils.closeQuietly(mediaStream);
            reader.dispose();
        }
    } else {
        log.error("No reader found for given format: " + suffix);
    }
    return result;
}

From source file:org.paxle.gui.impl.servlets.MetaDataIconServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response) {
    try {//from  ww w .  java2 s . com
        final Context context = this.getVelocityView().createContext(request, response);
        final String servicePID = request.getParameter(REQ_PARAM_SERVICEPID);

        if (servicePID != null) {
            // getting the metaDataTool
            final MetaDataTool tool = (MetaDataTool) context.get(MetaDataTool.TOOL_NAME);
            if (tool == null) {
                this.log("No MetaDataTool found");
                return;
            }

            final IMetaData metaData = tool.getMetaData(servicePID);
            if (metaData == null) {
                this.log(String.format("No metadata found for service with PID '%s'.", servicePID));
                return;
            }

            // getting the icon
            InputStream in = metaData.getIcon(16);
            if (in == null)
                in = this.getClass().getResourceAsStream("/resources/images/cog.png");

            // loading date
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout);
            bout.close();
            in.close();

            // trying to detect the mimetype of the image
            final ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            String contentType = URLConnection.guessContentTypeFromStream(bin);
            bin.close();

            // reading the image
            BufferedImage img = null;
            Iterator<ImageReader> readers = null;
            if (contentType != null) {
                readers = ImageIO.getImageReadersByMIMEType(contentType);
                while (readers != null && readers.hasNext() && img == null) {
                    // trying the next reader
                    ImageReader reader = readers.next();

                    InputStream input = null;
                    try {
                        input = new ByteArrayInputStream(bout.toByteArray());
                        reader.setInput(ImageIO.createImageInputStream(input));
                        img = reader.read(0);
                    } catch (Exception e) {
                        this.log(String.format("Unable to read metadata icon for service with PID '%s'.",
                                servicePID), e);
                    } finally {
                        if (input != null)
                            input.close();
                    }
                }
            }

            if (img != null) {
                response.setHeader("Content-Type", "image/png");
                ImageIO.write(img, "png", response.getOutputStream());
                return;
            } else {
                response.sendError(404);
                return;
            }
        } else {
            response.sendError(500, "Invalid usage");
        }
    } catch (Throwable e) {
        this.log(String.format("Unexpected '%s'.", e.getClass().getName()), e);
    }
}

From source file:org.deegree.tile.persistence.geotiff.ImageReaderFactory.java

@Override
public Object makeObject() throws Exception {
    ImageInputStream iis = null;/*from  ww  w  . j  a v a2  s  .c  o m*/
    ImageReader reader = null;
    Iterator<ImageReader> readers = getImageReadersBySuffix("tiff");
    while (readers.hasNext() && !(reader instanceof TIFFImageReader)) {
        reader = readers.next();
    }
    iis = createImageInputStream(file);
    // already checked in provider
    reader.setInput(iis);
    return reader;
}