Example usage for javax.imageio ImageIO getImageReadersByMIMEType

List of usage examples for javax.imageio ImageIO getImageReadersByMIMEType

Introduction

In this page you can find the example usage for javax.imageio ImageIO getImageReadersByMIMEType.

Prototype

public static Iterator<ImageReader> getImageReadersByMIMEType(String MIMEType) 

Source Link

Document

Returns an Iterator containing all currently registered ImageReader s that claim to be able to decode files with the given MIME type.

Usage

From source file:Main.java

public static boolean canReadMimeType(String mimeType) {
    Iterator iter = ImageIO.getImageReadersByMIMEType(mimeType);
    return iter.hasNext();
}

From source file:jails.http.converter.BufferedImageHttpMessageConverter.java

private boolean isReadable(MediaType mediaType) {
    if (mediaType == null) {
        return true;
    }/*  w  w  w. j ava2s  .  c o m*/
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(mediaType.toString());
    return imageReaders.hasNext();
}

From source file:jails.http.converter.BufferedImageHttpMessageConverter.java

public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    ImageInputStream imageInputStream = null;
    ImageReader imageReader = null;
    try {/*from  w  ww.j a  v a2 s. c  o  m*/
        imageInputStream = createImageInputStream(inputMessage.getBody());
        MediaType contentType = inputMessage.getHeaders().getContentType();
        Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
        if (imageReaders.hasNext()) {
            imageReader = imageReaders.next();
            ImageReadParam irp = imageReader.getDefaultReadParam();
            process(irp);
            imageReader.setInput(imageInputStream, true);
            return imageReader.read(0, irp);
        } else {
            throw new HttpMessageNotReadableException(
                    "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
        }
    } finally {
        if (imageReader != null) {
            imageReader.dispose();
        }
        if (imageInputStream != null) {
            try {
                imageInputStream.close();
            } catch (IOException ex) {
                // ignore
            }
        }
    }
}

From source file:com.joliciel.jochre.search.web.JochreSearchServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w  w w.  ja v a  2s . c o m
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");

        JochreSearchProperties props = JochreSearchProperties.getInstance(this.getServletContext());

        String command = req.getParameter("command");
        if (command == null) {
            command = "search";
        }

        if (command.equals("purge")) {
            JochreSearchProperties.purgeInstance();
            searcher = null;
            return;
        }

        Map<String, String> argMap = new HashMap<String, String>();
        @SuppressWarnings("rawtypes")
        Enumeration params = req.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = (String) params.nextElement();
            String value = req.getParameter(paramName);
            argMap.put(paramName, value);
        }

        SearchServiceLocator searchServiceLocator = SearchServiceLocator.getInstance();
        SearchService searchService = searchServiceLocator.getSearchService();

        double minWeight = 0;
        int titleSnippetCount = 1;
        int snippetCount = 3;
        int snippetSize = 80;
        boolean includeText = false;
        boolean includeGraphics = false;
        String snippetJson = null;
        Set<Integer> docIds = null;

        Set<String> handledArgs = new HashSet<String>();
        for (Entry<String, String> argEntry : argMap.entrySet()) {
            String argName = argEntry.getKey();
            String argValue = argEntry.getValue();
            argValue = URLDecoder.decode(argValue, "UTF-8");
            LOG.debug(argName + ": " + argValue);

            boolean handled = true;
            if (argName.equals("minWeight")) {
                minWeight = Double.parseDouble(argValue);
            } else if (argName.equals("titleSnippetCount")) {
                titleSnippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetCount")) {
                snippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetSize")) {
                snippetSize = Integer.parseInt(argValue);
            } else if (argName.equals("includeText")) {
                includeText = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("includeGraphics")) {
                includeGraphics = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("snippet")) {
                snippetJson = argValue;
            } else if (argName.equalsIgnoreCase("docIds")) {
                if (argValue.length() > 0) {
                    String[] idArray = argValue.split(",");
                    docIds = new HashSet<Integer>();
                    for (String id : idArray)
                        docIds.add(Integer.parseInt(id));
                }
            } else {
                handled = false;
            }
            if (handled) {
                handledArgs.add(argName);
            }
        }
        for (String argName : handledArgs)
            argMap.remove(argName);

        if (searcher == null) {
            String indexDirPath = props.getIndexDirPath();
            File indexDir = new File(indexDirPath);
            LOG.info("Index dir: " + indexDir.getAbsolutePath());
            searcher = searchService.getJochreIndexSearcher(indexDir);
        }

        if (command.equals("search")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            searcher.search(query, out);
            out.flush();
        } else if (command.equals("highlight") || command.equals("snippets")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            if (docIds == null)
                throw new RuntimeException("Command " + command + " requires docIds");

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(minWeight);
            highlightManager.setIncludeText(includeText);
            highlightManager.setIncludeGraphics(includeGraphics);
            highlightManager.setTitleSnippetCount(titleSnippetCount);
            highlightManager.setSnippetCount(snippetCount);
            highlightManager.setSnippetSize(snippetSize);

            Set<String> fields = new HashSet<String>();
            fields.add("text");

            if (command.equals("highlight"))
                highlightManager.highlight(highlighter, docIds, fields, out);
            else
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            out.flush();
        } else if (command.equals("imageSnippet")) {
            String mimeType = "image/png";
            response.setContentType(mimeType);
            if (snippetJson == null)
                throw new RuntimeException("Command " + command + " requires a snippet");
            Snippet snippet = new Snippet(snippetJson);

            if (LOG.isDebugEnabled()) {
                Document doc = searcher.getIndexSearcher().doc(snippet.getDocId());
                LOG.debug("Snippet in " + doc.get("id") + ", path: " + doc.get("path"));
            }

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            ImageSnippet imageSnippet = highlightManager.getImageSnippet(snippet);
            OutputStream os = response.getOutputStream();
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            BufferedImage image = imageSnippet.getImage();
            ImageReader imageReader = ImageIO.getImageReadersByMIMEType(mimeType).next();
            ImageWriter imageWriter = ImageIO.getImageWriter(imageReader);
            imageWriter.setOutput(ios);
            imageWriter.write(image);
            ios.flush();
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    }
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Private method which seeks through the supported image readers to check
 * if a there is a reader which handles the specified MIME. This method
 * checks spe- cifically for JPG or PNG images because Sun's Java supports
 * two kind of readers for these particular formats. And because one of
 * these readers doesn't function well, we need to be sure we have the right
 * reader.//from w w  w .ja  v a2s .co m
 *
 * @param mime String with the MIME to find.
 *
 * @return ImageReader which can handle the specified MIME or null if no
 * reader was found.
 */
// <editor-fold defaultstate="" desc="getJPGOrPNGReader(String mime) method.">
private static ImageReader getJPGOrPNGReader(String mime) {
    Iterator it = ImageIO.getImageReadersByMIMEType(mime);
    ImageReader imTest = null;
    String name = null;
    while (it.hasNext()) {
        imTest = (ImageReader) it.next();
        name = imTest.getClass().getPackage().getName();
        String generalPackage = name.substring(0, name.lastIndexOf("."));
        if (generalPackage.equalsIgnoreCase("com.sun.media.imageioimpl.plugins")) {
            continue;
        }
    }
    //log.info("Using ImageReader: " + name);
    return imTest;
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Private method which seeks through the supported image readers to check
 * if a there is a reader which handles the specified MIME. This method
 * checks spe- cifically for GIF or TIFF images.
 *
 * @param mime String with the MIME to find.
 *
 * @return ImageReader which can handle the specified MIME or null if no
 * reader was found./*from  w w  w . j  a v  a  2s . com*/
 */
// <editor-fold defaultstate="" desc="getGIFOrTIFFReader(String mime) method.">
private static ImageReader getGIFOrTIFFReader(String mime) {
    Iterator it = ImageIO.getImageReadersByMIMEType(mime);
    ImageReader imTest = null;
    String name = null;
    while (it.hasNext()) {
        imTest = (ImageReader) it.next();
        name = imTest.getClass().getPackage().getName();
    }
    //log.info("Using ImageReader: " + name);
    return imTest;
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Private method which seeks through the supported image writers to check
 * if a there is a writers which handles the specified MIME. This method
 * checks spe- cifically for JPG or PNG images because Sun's Java supports
 * two kind of writers for these particular formats. And because one of
 * these writers doesn't function well, we need to be sure we have the right
 * writers.//from  w ww.  ja v  a2s  .  c o  m
 *
 * @param mime String with the MIME to find.
 *
 * @return ImageWriter which can handle the specified MIME or null if no
 * writer was found.
 */
// <editor-fold defaultstate="" desc="getJPGOrPNGWriter(String mime) method.">
private ImageWriter getJPGOrPNGWriter(String mime) {
    Iterator it = ImageIO.getImageReadersByMIMEType(mime);
    ImageWriter imTest = null;
    while (it.hasNext()) {
        imTest = (ImageWriter) it.next();
        String name = imTest.getClass().getPackage().getName();
        String generalPackage = name.substring(0, name.lastIndexOf("."));
        if (generalPackage.equalsIgnoreCase("com.sun.media.imageioimpl.plugins")) {
            continue;
        }
    }
    return imTest;
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Private method which seeks through the supported image writers to check
 * if a there is a writers which handles the specified MIME. This method
 * checks spe- cifically for GIF or TIFF images.
 *
 * @param mime String with the MIME to find.
 *
 * @return ImageWriter which can handle the specified MIME or null if no
 * writer was found.//  ww  w .j  a v  a  2s .  c  o m
 */
// <editor-fold defaultstate="" desc="getGIFOrTIFFWriter(String mime) method.">
private ImageWriter getGIFOrTIFFWriter(String mime) {
    Iterator it = ImageIO.getImageReadersByMIMEType(mime);
    ImageWriter imTest = null;
    while (it.hasNext()) {
        imTest = (ImageWriter) it.next();
    }
    return imTest;
}

From source file:org.apache.tika.parser.image.ImageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        // If the old (pre-RFC7903) BMP mime type is given,
        //  fix it up to the new one, so Java is happy
        if (OLD_BMP_TYPE.toString().equals(type)) {
            type = MAIN_BMP_TYPE.toString();
        }//w  w  w . ja v  a 2  s . c o  m

        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    try (ImageInputStream imageStream = ImageIO
                            .createImageInputStream(new CloseShieldInputStream(stream))) {
                        reader.setInput(imageStream);

                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));

                        loadMetadata(reader.getImageMetadata(0), metadata);
                    }
                } finally {
                    reader.dispose();
                }
            }

            // Translate certain Metadata tags from the ImageIO
            //  specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            // TIKA-619: There is a known bug in the Sun API when dealing with GIF images
            //  which Tika will just ignore.
            if (!(e.getMessage() != null && e.getMessage().equals("Unexpected block type 0!")
                    && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
    }

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();
    xhtml.endDocument();
}

From source file:org.exoplatform.wcm.ext.component.activity.FileUIActivity.java

protected int getImageWidth(Node node) {
    int imageWidth = 0;
    try {/*from  ww w .j ava2  s. c  o m*/
        if (node.hasNode(NodetypeConstant.JCR_CONTENT))
            node = node.getNode(NodetypeConstant.JCR_CONTENT);
        ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next();
        ImageInputStream iis = ImageIO.createImageInputStream(node.getProperty("jcr:data").getStream());
        reader.setInput(iis, true);
        imageWidth = reader.getWidth(0);
        iis.close();
        reader.dispose();
    } catch (Exception e) {
        LOG.info("Cannot get node");
    }
    return imageWidth;
}