Example usage for javax.imageio.stream ImageOutputStream flush

List of usage examples for javax.imageio.stream ImageOutputStream flush

Introduction

In this page you can find the example usage for javax.imageio.stream ImageOutputStream flush.

Prototype

void flush() throws IOException;

Source Link

Document

Discards the initial position of the stream prior to the current stream position.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    BufferedImage bi = ImageIO.read(url);
    for (float q = 0.2f; q < .9f; q += .2f) {
        OutputStream outStream = new FileOutputStream(new File("c:/Java_Dev/Image-" + q + ".jpg"));
        ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
        imgWriter.setOutput(ioStream);/*from   ww  w  .  j  a  v a2s.c  o  m*/

        JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
        jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(q);

        imgWriter.write(null, new IIOImage(bi, null, null), jpegParams);

        ioStream.flush();
        ioStream.close();
        imgWriter.dispose();
    }
}

From source file:Main.java

private static void writeJpegCompressedImage(BufferedImage image, String outFile) throws IOException {
    float qualityFloat = 1f;
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
    ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
    imgWriter.setOutput(ioStream);/*from  ww  w  .java  2 s .c  o  m*/

    JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
    jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpegParams.setCompressionQuality(qualityFloat);

    imgWriter.write(null, new IIOImage(image, null, null), jpegParams);

    ioStream.flush();
    ioStream.close();
    imgWriter.dispose();

    OutputStream outputStream = new FileOutputStream(outFile);
    outStream.writeTo(outputStream);

}

From source file:com.db.comserv.main.utilities.HttpCaller.java

public static String compress(String imageString, float quality) throws IOException {
    byte[] imageByte = Base64.decodeBase64(imageString);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    BufferedImage image = ImageIO.read(bis);
    bis.close();/*from   w ww. ja  v a 2s. c o  m*/

    // Get a ImageWriter for given extension format.

    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpg");
    if (!writers.hasNext())
        throw new IllegalStateException("No writers found");

    ImageWriter writer = (ImageWriter) writers.next();
    // Create the ImageWriteParam to compress the image.
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);

    // The output will be a ByteArrayOutputStream (in memory)
    ByteArrayOutputStream bos = new ByteArrayOutputStream(32768);
    ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), param);
    ios.flush(); // otherwise the buffer size will be zero!
    byte[] encodedBytes = Base64.encodeBase64(bos.toByteArray());

    return new String(encodedBytes);
}

From source file:ImageUtilities.java

/**
 * Writes an image to an output stream as a JPEG file. The JPEG quality can
 * be specified in percent.// w  ww.  j  a v  a2s. c  om
 * 
 * @param image
 *            image to be written
 * @param stream
 *            target stream
 * @param qualityPercent
 *            JPEG quality in percent
 * 
 * @throws IOException
 *             if an I/O error occured
 * @throws IllegalArgumentException
 *             if qualityPercent not between 0 and 100
 */
public static void saveImageAsJPEG(BufferedImage image, OutputStream stream, int qualityPercent)
        throws IOException {
    if ((qualityPercent < 0) || (qualityPercent > 100)) {
        throw new IllegalArgumentException("Quality out of bounds!");
    }
    float quality = qualityPercent / 100f;
    ImageWriter writer = null;
    Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    }
    ImageOutputStream ios = ImageIO.createImageOutputStream(stream);
    writer.setOutput(ios);
    ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwparam.setCompressionQuality(quality);
    writer.write(null, new IIOImage(image, null, null), iwparam);
    ios.flush();
    writer.dispose();
    ios.close();
}

From source file:com.openkm.applet.Util.java

/**
 * Upload scanned document to OpenKM//from w w  w . j  av  a 2  s. c  om
 * 
 */
public static String createDocument(String token, String path, String fileName, String fileType, String url,
        List<BufferedImage> images) throws MalformedURLException, IOException {
    log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", "
            + images + ")");
    File tmpDir = createTempDir();
    File tmpFile = new File(tmpDir, fileName + "." + fileType);
    ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile);
    String response = "";

    try {
        if ("pdf".equals(fileType)) {
            ImageUtils.writePdf(images, ios);
        } else if ("tif".equals(fileType)) {
            ImageUtils.writeTiff(images, ios);
        } else {
            if (!ImageIO.write(images.get(0), fileType, ios)) {
                throw new IOException("Not appropiated writer found!");
            }
        }

        ios.flush();
        ios.close();

        if (token != null) {
            // Send image
            HttpClient client = new DefaultHttpClient();
            MultipartEntity form = new MultipartEntity();
            form.addPart("file", new FileBody(tmpFile));
            form.addPart("path", new StringBody(path, Charset.forName("UTF-8")));
            form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT
            HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token);
            post.setHeader("Cookie", "jsessionid=" + token);
            post.setEntity(form);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = client.execute(post, responseHandler);
        } else {
            // Store in disk
            String home = System.getProperty("user.home");
            File dst = new File(home, tmpFile.getName());
            copyFile(tmpFile, dst);
            response = "Image copied to " + dst.getPath();
        }
    } finally {
        FileUtils.deleteQuietly(tmpDir);
    }

    log.info("createDocument: " + response);
    return response;
}

From source file:ImageUtils.java

/**
 * Compress and save an image to the disk. Currently this method only supports JPEG images.
 * /*  ww  w.  j a v a 2  s . co  m*/
 * @param image The image to save
 * @param toFileName The filename to use
 * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
 * or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
 */
public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
        if (type == IMAGE_PNG) {
            throw new UnsupportedOperationException("PNG compression not implemented");
        }

        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer;
        writer = (ImageWriter) iter.next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
        writer.setOutput(ios);

        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(0.7F);

        writer.write(null, new IIOImage(image, null, null), iwparam);

        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi//from   w w w  . j av  a  2  s. co m
 * @param filename
 * @param dEncRate
 * @param lossless
 * @throws IOException
 */
public static void storeBIAsJP2File(BufferedImage bi, String filename, double dEncRate, boolean lossless)
        throws IOException {

    if (hasJPEG2000FileTag(filename)) {

        IIOImage iioImage = new IIOImage(bi, null, null);

        ImageWriter jp2iw = ImageIO.getImageWritersBySuffix("jp2").next();
        J2KImageWriteParam writeParam = (J2KImageWriteParam) jp2iw.getDefaultWriteParam();

        // Indicates using the lossless scheme or not. It is equivalent to use reversible quantization and 5x3 integer wavelet filters. The default is true.
        writeParam.setLossless(lossless);

        if (lossless)
            writeParam.setFilter(J2KImageWriteParam.FILTER_53); // Specifies which wavelet filters to use for the specified tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters.
        else
            writeParam.setFilter(J2KImageWriteParam.FILTER_97);

        if (!lossless) {
            // The bitrate in bits-per-pixel for encoding. Should be set when lossy compression scheme is used. With the default value Double.MAX_VALUE, a lossless compression will be done.
            writeParam.setEncodingRate(dEncRate);

            // changes in compression rate are done in the following way
            // however JPEG2000 implementation seems not to support this <-- no differences visible
            //                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //                writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            //                writeParam.setCompressionQuality(1.0f);
        }

        ImageOutputStream ios = null;
        try {
            ios = new FileImageOutputStream(new File(filename));
            jp2iw.setOutput(ios);
            jp2iw.write(null, iioImage, writeParam);
            jp2iw.dispose();
            ios.flush();
        } finally {
            if (ios != null)
                ios.close();
        }
    } else
        System.err.println("please name your file as valid JPEG2000 file: ends with .jp2");
}

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 .ja v a2 s  . 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:com.joliciel.jochre.search.web.JochreSearchServlet.java

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

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

/**
 * // w  w  w. j  a v  a 2 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());
    }

}