Example usage for javax.imageio ImageWriter setOutput

List of usage examples for javax.imageio ImageWriter setOutput

Introduction

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

Prototype

public void setOutput(Object output) 

Source Link

Document

Sets the destination to the given ImageOutputStream or other Object .

Usage

From source file:net.d53dev.dslfy.web.service.GifService.java

public void saveAnimatedGIF(OutputStream out, List<GifFrame> frames, int loopCount) throws Exception {
    ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();

    ImageOutputStream ios = ImageIO.createImageOutputStream(out);
    iw.setOutput(ios);
    iw.prepareWriteSequence(null);// w w w  .  j av a2  s  .  com

    int p = 0;
    for (GifFrame frame : frames) {
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        IIOMetadata metadata = iw.getDefaultImageMetadata(new ImageTypeSpecifier(frame.img), iwp);
        this.configureGIFFrame(metadata, String.valueOf(frame.delay / 10L), p++, frame.disposalMethod,
                loopCount);
        IIOImage ii = new IIOImage(frame.img, null, metadata);
        iw.writeToSequence(ii, null);
    }

    iw.endWriteSequence();
    ios.close();
}

From source file:compressor.Compressor.java

void compress_images(String src, String dest) throws IOException {

    File f = null;//w  ww  .  j a v a  2s .  co m
    String[] paths;

    try {
        // create new file
        f = new File(src);

        // array of files and directory
        paths = f.list();

        File file = new File(dest + "compressed");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        dest = dest + "compressed/";

        // for each name in the path array
        for (String path : paths) {
            // prints filename and directory name

            File input = new File(src + path);
            BufferedImage image = ImageIO.read(input);

            File compressedImageFile = new File(dest + path);
            OutputStream os = new FileOutputStream(compressedImageFile);

            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = (ImageWriter) writers.next();

            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.05f);
            writer.write(null, new IIOImage(image, null, null), param);

            os.close();
            ios.close();
            writer.dispose();

        }
    } catch (Exception e) {
    }

}

From source file:org.deegree.securityproxy.wms.responsefilter.clipping.SimpleRasterClipper.java

private void writeImage(OutputStream destination, String format, BufferedImage outputImage)
        throws ClippingException, IOException {
    ImageWriter imageWriter = createImageWriter(format);
    ImageWriteParam writerParam = configureWriterParameters(format, imageWriter);
    imageWriter.setOutput(ImageIO.createImageOutputStream(destination));
    imageWriter.write(null, new IIOImage(outputImage, null, null), writerParam);
    imageWriter.dispose();/* ww w  . j av  a  2s.co  m*/
}

From source file:org.egov.works.abstractestimate.service.EstimatePhotographService.java

public File compressImage(final MultipartFile[] files) throws IOException, FileNotFoundException {

    final BufferedImage image = ImageIO.read(files[0].getInputStream());
    final File compressedImageFile = new File(files[0].getOriginalFilename());
    final OutputStream os = new FileOutputStream(compressedImageFile);
    String fileExtenstion = files[0].getOriginalFilename();
    fileExtenstion = fileExtenstion.substring(fileExtenstion.lastIndexOf(".") + 1);
    final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(fileExtenstion);
    final ImageWriter writer = writers.next();
    final ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);
    final ImageWriteParam param = writer.getDefaultWriteParam();

    if (!fileExtenstion.equalsIgnoreCase("png")) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.5f);
    }/* w  w w . j a va  2 s  .c o m*/
    writer.write(null, new IIOImage(image, null, null), param);

    os.close();
    ios.close();
    writer.dispose();
    return compressedImageFile;
}

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);/*from   w ww  .j a  v  a  2s  .  com*/
        imageOutputStream.close();
    } 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 w  w w. j a  va  2  s.com*/
 *            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:net.rptools.lib.net.FTPLocation.java

public void putContent(ImageWriter writer, BufferedImage content) throws IOException {
    OutputStream os = null;/*w  w w  .  j a  v a 2  s  . c  o 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.shredzone.cilla.service.resource.ImageProcessorImpl.java

/**
 * Writes a JPEG file with adjustable compression quality.
 *
 * @param image// w w  w . java2 s  .c  o m
 *            {@link BufferedImage} to write
 * @param out
 *            {@link ImageOutputStream} to write to
 * @param quality
 *            Compression quality between 0.0f (worst) and 1.0f (best)
 */
private void jpegQualityWriter(BufferedImage image, ImageOutputStream out, float quality) throws IOException {
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();

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

    IIOImage ioImage = new IIOImage(image, null, null);

    writer.setOutput(out);
    writer.write(null, ioImage, iwp);
    writer.dispose();
}

From source file:gr.iti.mklab.reveal.forensics.util.Util.java

public static BufferedImage recompressImage(BufferedImage imageIn, int quality) {
    // Apply in-memory JPEG compression to a BufferedImage given a quality setting (0-100)
    // and return the resulting BufferedImage
    float fQuality = (float) (quality / 100.0);
    BufferedImage outputImage = null;
    try {//  w  ww .  ja v a  2  s  . c o  m
        ImageWriter writer;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
        writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(fQuality);
        byte[] imageInByte;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(baos);
            writer.setOutput(mcios);
            IIOImage tmpImage = new IIOImage(imageIn, null, null);
            writer.write(null, tmpImage, iwp);
            writer.dispose();
            baos.flush();
            imageInByte = baos.toByteArray();
        }
        InputStream in = new ByteArrayInputStream(imageInByte);
        outputImage = ImageIO.read(in);
    } catch (Exception ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    return outputImage;
}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w w w  . j  a  v  a  2s . c om*/
        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;
    }
}