Example usage for java.awt.image BufferedImage flush

List of usage examples for java.awt.image BufferedImage flush

Introduction

In this page you can find the example usage for java.awt.image BufferedImage flush.

Prototype

public void flush() 

Source Link

Document

Flushes all reconstructable resources being used by this Image object.

Usage

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

private Element createEmbeddeImage(BufferedImage img) {
    if (img == null) {
        return null;
    }//from   ww w.  j  av a  2s  .c  om

    int width = img.getWidth();
    int height = img.getHeight();
    ImageWriter iw = ImageWriterFactory.instance().createByFormatName("png"); //$NON-NLS-1$
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192 * 2);
    String sUrl = null;
    try {
        final ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos);
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        iw.setOutput(ios);
        iw.write((IIOMetadata) null, new IIOImage(img, null, null), iwp);
        img.flush();
        ios.close();
        sUrl = SVGImage.BASE64 + new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception ex) {
        logger.log(ex);
    } finally {
        iw.dispose();
    }

    Element elemG = dom.createElement("g"); //$NON-NLS-1$
    elemG.setAttribute("id", "img_" + img.hashCode()); //$NON-NLS-1$//$NON-NLS-2$
    Element elem = dom.createElement("image"); //$NON-NLS-1$
    elem.setAttribute("x", "0"); //$NON-NLS-1$//$NON-NLS-2$
    elem.setAttribute("y", "0"); //$NON-NLS-1$ //$NON-NLS-2$
    elem.setAttribute("width", Integer.toString(width)); //$NON-NLS-1$
    elem.setAttribute("height", Integer.toString(height)); //$NON-NLS-1$
    elem.setAttribute("xlink:href", sUrl); //$NON-NLS-1$
    elemG.appendChild(elem);

    return elemG;
}

From source file:org.eclipse.wb.internal.swing.model.property.editor.beans.PropertyEditorWrapper.java

private Image paintValue(GC gc, int width, int height) throws Exception {
    // create AWT graphics
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = (Graphics2D) image.getGraphics();
    // prepare color's
    Color background = gc.getBackground();
    Color foreground = gc.getForeground();
    // fill graphics
    graphics2D.setColor(SwingUtils.getAWTColor(background));
    graphics2D.fillRect(0, 0, width, height);
    // set color//www .j  a v a  2s.c  o m
    graphics2D.setBackground(SwingUtils.getAWTColor(background));
    graphics2D.setColor(SwingUtils.getAWTColor(foreground));
    // set font
    FontData[] fontData = gc.getFont().getFontData();
    String name = fontData.length > 0 ? fontData[0].getName() : "Arial";
    graphics2D.setFont(new java.awt.Font(name, java.awt.Font.PLAIN, graphics2D.getFont().getSize() - 1));
    // paint image
    m_propertyEditor.paintValue(graphics2D, new java.awt.Rectangle(0, 0, width, height));
    // conversion
    try {
        return SwingImageUtils.convertImage_AWT_to_SWT(image);
    } finally {
        image.flush();
        graphics2D.dispose();
    }
}

From source file:org.exoplatform.wcm.connector.viewer.PDFViewerRESTService.java

private File buildFileImage(File input, String path, String pageNumber, String strRotation, String strScale) {
    Document document = buildDocumentImage(input, path);

    // Turn off Log of org.icepdf.core.pobjects.Stream to not print error stack trace in case
    // viewing a PDF file including CCITT (Fax format) images
    // TODO: Remove these statement and comments after IcePDF fix ECMS-3765
    Logger.getLogger(Stream.class.toString()).setLevel(Level.OFF);

    // save page capture to file.
    float scale = 1.0f;
    try {//  w ww  .  jav a 2 s. co m
        scale = Float.parseFloat(strScale);
        // maximum scale support is 300%
        if (scale > 3.0f) {
            scale = 3.0f;
        }
    } catch (NumberFormatException e) {
        scale = 1.0f;
    }
    float rotation = 0.0f;
    try {
        rotation = Float.parseFloat(strRotation);
    } catch (NumberFormatException e) {
        rotation = 0.0f;
    }
    int maximumOfPage = document.getNumberOfPages();
    int pageNum = 1;
    try {
        pageNum = Integer.parseInt(pageNumber);
    } catch (NumberFormatException e) {
        pageNum = 1;
    }
    if (pageNum >= maximumOfPage)
        pageNum = maximumOfPage;
    else if (pageNum < 1)
        pageNum = 1;
    // Paint each pages content to an image and write the image to file
    BufferedImage image = (BufferedImage) document.getPageImage(pageNum - 1, GraphicsRenderingHints.SCREEN,
            Page.BOUNDARY_CROPBOX, rotation, scale);
    RenderedImage rendImage = image;
    File file = null;
    try {
        file = File.createTempFile("imageCapture1_" + pageNum, ".png");
        /*
        file.deleteOnExit();
          PM Comment : I removed this line because each deleteOnExit creates a reference in the JVM for future removal
          Each JVM reference takes 1KB of system memory and leads to a memleak
        */
        ImageIO.write(rendImage, "png", file);
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e);
        }
    } finally {
        image.flush();
        // clean up resources
        document.dispose();
    }
    return file;
}

From source file:org.forumj.web.servlet.post.SetAvatar.java

private void writeImageToFile(ImageSize destSize, int imgType, Image image, String fileName, String imageFormat)
        throws IOException {
    File destFile = new File(fileName);
    OutputStream out = null;/*from   w ww. j  a  v  a2  s . c  om*/
    BufferedImage destImage = null;
    try {
        out = new FileOutputStream(destFile);
        destImage = renderImage(destSize, imgType, image);
        ImageIO.write(destImage, imageFormat, out);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (destImage != null)
            destImage.flush();
    }
}

From source file:org.jahia.modules.dm.thumbnails.impl.DocumentThumbnailServiceImpl.java

public boolean createThumbnailForNode(JCRNodeWrapper fileNode, String thumbnailName, int thumbnailSize)
        throws RepositoryException, DocumentOperationException {
    if (!canHandle(fileNode)) {
        return false;
    }/*w ww  .jav a  2 s  . c o  m*/

    long timer = System.currentTimeMillis();

    JCRNodeWrapper thumbNode = null;

    BufferedImage image = null;
    BufferedImage thumbnail = null;
    try {
        image = getImageOfFirstPageForNode(fileNode);

        if (image != null) {
            thumbnail = imageService.resizeImage(image, thumbnailSize, thumbnailSize, ResizeType.ADJUST_SIZE);
            thumbNode = storeThumbnailNode(fileNode, thumbnail, thumbnailName);
            if (logger.isDebugEnabled()) {
                logger.debug("Generated thumbnail {} for node {} in {} ms", new Object[] { thumbNode.getPath(),
                        fileNode.getPath(), (System.currentTimeMillis() - timer) });
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (image != null) {
            image.flush();
        }
        if (thumbnail != null) {
            thumbnail.flush();
        }
    }

    return thumbNode != null;
}

From source file:org.jahia.modules.docviewer.DocumentViewService.java

/**
 * Generates thumbnails for the specified document node.
 * /*w  w  w.  j  ava  2s  .  c  o m*/
 * @param fileNode
 *            the node to generate thumbnails for
 * @param thumbnailName
 *            the name of the thumbnail node
 * @param thumbnailSize
 *            the size of the generated thumbnail
 * @throws RepositoryException
 *             in case of an error
 */
public void createThumbnail(JCRNodeWrapper fileNode, String thumbnailName, int thumbnailSize)
        throws RepositoryException {
    if (!isEnabled() || supportedDocumentFormats == null) {
        logger.info("Conversion service is not enabled." + " Skip converting node {}", fileNode.getPath());
        return;
    }

    long timer = System.currentTimeMillis();

    if (fileNode.isNodeType("nt:file")
            && isMimeTypeGroup(fileNode.getFileContent().getContentType(), supportedDocumentFormats)) {
        BufferedImage image = null;
        BufferedImage thumbnail = null;
        try {
            image = getImageOfFirstPage(fileNode);

            if (image != null) {
                thumbnail = Thumbnails.of(image).size(thumbnailSize, thumbnailSize).asBufferedImage();
                JCRNodeWrapper thumbNode = storeThumbnailNode(fileNode, thumbnail, thumbnailName);
                if (logger.isDebugEnabled()) {
                    logger.debug("Generated thumbnail {} for node {} in {} ms", new Object[] {
                            thumbNode.getPath(), fileNode.getPath(), (System.currentTimeMillis() - timer) });
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (image != null) {
                image.flush();
            }
            if (thumbnail != null) {
                thumbnail.flush();
            }
        }
    } else {
        logger.warn(
                "Path should correspond to a file node with one"
                        + " of the supported formats {}. Skipping node {}",
                supportedDocumentFormats, fileNode.getPath());
    }
}

From source file:org.jajuk.base.Album.java

/**
 * Gets the thumbnail.//from w  ww . j a v  a  2s  .c o  m
 * 
 * @param size size using format width x height
 * 
 * @return album thumb for given size
 */
public ImageIcon getThumbnail(int size) {
    File fCover = ThumbnailManager.getThumbBySize(this, size);
    // Check if thumb already exists
    if (!fCover.exists() || fCover.length() == 0) {
        return IconLoader.getNoCoverIcon(size);
    }
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File(fCover.getAbsolutePath()));
    } catch (IOException e) {
        Log.error(e);
    }
    // can be null now if an error occurred, we reported a error to the log
    // already...
    if (img == null) {
        return null;
    }
    ImageIcon icon = new ImageIcon(img);
    // Free thumb memory (DO IT AFTER FULL ImageIcon loading)
    img.flush();
    return icon;
}

From source file:org.jajuk.ui.thumbnails.LastFmAlbumThumbnail.java

/**
 * Long part of the populating process. Longest parts (images download) should
 * have already been done by the caller outside the EDT. we only pop the image
 * from the cache here.//from w  ww. j  ava 2 s .  c om
 */
private void preLoad() {
    try {
        // Check if album image is null
        String albumUrl = album.getBigCoverURL();
        if (StringUtils.isBlank(albumUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(albumUrl);
        // Download image and store file reference (to generate the
        // popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (!fCover.exists()) {
            Log.warn("Cache file not found: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        if (fCover.length() == 0) {
            Log.warn("Cache file has zero bytes: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read cover from: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        ii = UtilGUI.getScaledImage(downloadedImage, 100);
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (FileNotFoundException e) {
        // only report a warning for FileNotFoundException and do not show a
        // stack trace in the logfile as it is happening frequently
        Log.warn("Could not load image, no content found at address: {{" + e.getMessage() + "}}");
    } catch (SocketTimeoutException e) {
        // only report a warning for FileNotFoundException and do not show a
        // stacktrace in the logfile as it is happening frequently
        Log.warn("Could not load image, timed out while reading address: {{" + e.getMessage() + "}}");
    } catch (IOException e) {
        if (e.getMessage().contains(" 403 ")) {
            Log.warn("Could not access webpage, returned error 403: " + e.getMessage());
        } else {
            Log.error(e);
        }
    } catch (Exception e) {
        Log.error(e);
        // check for empty file to remove invalid cache entries
        if (fCover.exists() && fCover.length() == 0) {
            Log.warn("Removing empty file from cache: " + fCover.getAbsolutePath());
            if (!fCover.delete()) {
                Log.warn("Error removing file: " + fCover.getAbsolutePath());
            }
        }
    }
}

From source file:org.jajuk.ui.thumbnails.LastFmArtistThumbnail.java

/**
 * Long part of the populating process. Longest parts (images download) should
 * have already been done by the caller outside the EDT. we only pop the image
 * from the cache here./*  w  w  w. j  a v a 2s  . com*/
 */
private void preLoad() {
    try {
        // Check if artist is null
        String artistUrl = artist.getImageUrl();
        if (StringUtils.isBlank(artistUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(artistUrl);
        // Download the picture and store file reference (to
        // generate the popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (fCover == null) {
            Log.warn("Could not read remote file: {{" + remote.toString() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read image data in file: {{" + fCover + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        // In artist view, do not reduce artist picture
        if (isArtistView()) {
            ii = downloadedImage;
        } else {
            ii = UtilGUI.getScaledImage(downloadedImage, 100);
        }
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (IIOException e) {
        // report IIOException only as warning here as we can expect this to
        // happen frequently with images on the net
        Log.warn("Could not read image: {{" + artist.getImageUrl() + "}} Cache: {{" + fCover + "}}",
                e.getMessage());
    } catch (UnknownHostException e) {
        Log.warn("Could not contact host for loading images: {{" + e.getMessage() + "}}");
    } catch (Exception e) {
        Log.error(e);
    }
}

From source file:org.niord.core.repo.ThumbnailService.java

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file/* www.j a  v a2s  . com*/
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            ImageIO.write(thumbImage, FilenameUtils.getExtension(thumbFile.getFileName().toString()),
                    thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}