Example usage for javax.imageio ImageWriter write

List of usage examples for javax.imageio ImageWriter write

Introduction

In this page you can find the example usage for javax.imageio ImageWriter write.

Prototype

public void write(RenderedImage image) throws IOException 

Source Link

Document

Appends a complete image stream consisting of a single image with default metadata and thumbnails to the output.

Usage

From source file:com.t3.net.FTPLocation.java

@Override
public void putContent(ImageWriter writer, BufferedImage image) {
    try (OutputStream os = new URL(composeFileLocation()).openConnection().getOutputStream()) {
        writer.setOutput(os);/*from  w  ww. jav a2s. co  m*/
        writer.write(image);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.rptools.lib.net.FTPLocation.java

public void putContent(ImageWriter writer, BufferedImage content) throws IOException {
    OutputStream os = null;//w w w. ja  va  2 s  .co m
    try {
        //         os = composeURL().openConnection().getOutputStream();
        os = new URL(composeFileLocation()).openConnection().getOutputStream();
        writer.setOutput(os);
        writer.write(content);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.jahia.services.image.AbstractJava2DImageService.java

protected void saveImageToFile(BufferedImage dest, String mimeType, File destFile) throws IOException {
    Iterator<ImageWriter> suffixWriters = ImageIO.getImageWritersByMIMEType(mimeType);
    if (suffixWriters.hasNext()) {
        ImageWriter imageWriter = suffixWriters.next();
        ImageOutputStream imageOutputStream = new FileImageOutputStream(destFile);
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(dest);
        imageOutputStream.close();//w  w w  .j  a v  a2s.  c o  m
    } else {
        logger.warn(
                "Couldn't find a writer for mime type : " + mimeType + "(" + this.getClass().getName() + ")");
    }
}

From source file:wicket.contrib.jasperreports.JRImageResource.java

/**
 * @param image/*from   www .  j a va 2s. c o  m*/
 *            The image to turn into data
 * 
 * @return The image data for this dynamic image
 */
protected byte[] toImageData(final BufferedImage image) {
    try {
        // Create output stream
        final ByteArrayOutputStream out = new ByteArrayOutputStream();

        // Get image writer for format
        final ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(format).next();

        // Write out image
        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write(image);

        // Return the image data
        return out.toByteArray();
    } catch (IOException e) {
        throw new WicketRuntimeException("Unable to convert dynamic image to stream", e);
    }
}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w  ww. jav a  2 s  .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:com.alkacon.opencms.v8.weboptimization.CmsOptimizationSprite.java

/**
 * Writes the given image as of the given type to the servlet output stream.<p>
 * //from w  ww .  j  a  va 2s .  c om
 * @param image the image to write
 * @param type the type
 * 
 * @throws IOException if something goes wrong
 */
protected void writeImage(BufferedImage image, String type) throws IOException {

    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(type).next();
    ImageOutputStream stream = ImageIO.createImageOutputStream(getJspContext().getResponse().getOutputStream());
    writer.setOutput(stream);
    writer.write(image);
    // We must close the stream now because if we are wrapping a ServletOutputStream,
    // a future gc can commit a stream that used in another thread (very very bad)
    stream.flush();
    stream.close();
    writer.dispose();
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * @param image//from   www.ja  va 2  s . c o m
 *            The image to turn into data
 * @return The image data for this dynamic image
 */
protected byte[] toImageData(final BufferedImage image) throws IOException {
    // Create output stream
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    String format = config.getImageFormat().substring(1);
    // Get image writer for format
    // FIXME: config.getImageFormat()
    final ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(format).next();

    // Write out image
    writer.setOutput(ImageIO.createImageOutputStream(out));
    writer.write(image);

    // Return the image data
    return out.toByteArray();
}

From source file:ImageIOTest.java

/**
 * Save the current image in a file/*from w  w w.  j a  v a  2  s  .c om*/
 * @param formatName the file format
 */
public void saveFile(final String formatName) {
    if (images == null)
        return;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatName);
    ImageWriter writer = iter.next();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = writer.getOriginatingProvider().getFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));

    int r = chooser.showSaveDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    try {
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(f);
        writer.setOutput(imageOut);

        writer.write(new IIOImage(images[0], null, null));
        for (int i = 1; i < images.length; i++) {
            IIOImage iioImage = new IIOImage(images[i], null, null);
            if (writer.canInsertImage(i))
                writer.writeInsert(i, iioImage, null);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
}

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

/**
 * /*from w  ww . j  av a2 s  .  c  o  m*/
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

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

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java

/**
 * This method create thumbImage of the image file given and save it in outFile.
 * Compression quality is also given. thumbBounds is used for calculating the size of the thumb.
 * //from www .  ja v  a2s  . c  om
 * @param infile slide image to create thumb
 * @param outfile output thumb file
 * @param compressionQuality the compression quality
 * @param thumbBounds the thumb bounds
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds)
        throws IOException {
    // Retrieve jpg image to be resized
    Image image = ImageIO.read(infile);

    // get original image size for thumb size calculation
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);

    float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight);

    int thumbWidth = (int) (imageWidth * thumbRatio);
    int thumbHeight = (int) (imageHeight * thumbRatio);

    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    // Find a jpeg writer
    ImageWriter writer = null;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    }

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(compressionQuality);

    // Prepare output file
    ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
    writer.setOutput(ios);
    // write to the thumb image 
    writer.write(thumbImage);

    // Cleanup
    ios.flush();
    writer.dispose();
    ios.close();
}