Java JComponent to Image componentToImage(Component c)

Here you can find the source of componentToImage(Component c)

Description

Sometimes you want a laid out component as an image.

License

Open Source License

Parameter

Parameter Description
c The given component to turn into an image.

Return

a BufferedImage instance.

Declaration

public static BufferedImage componentToImage(Component c) 

Method Source Code


//package com.java2s;
/*//  w  ww  .  j av  a  2  s . c  o m
This file is part of JFLICKS.
    
JFLICKS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
JFLICKS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with JFLICKS.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.awt.AlphaComposite;
import java.awt.Component;

import java.awt.Dimension;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Sometimes you want a laid out component as an image.  Suitable for
     * printing or saving to disk etc.
     *
     * @param c The given component to turn into an image.
     * @return a BufferedImage instance.
     */
    public static BufferedImage componentToImage(Component c) {

        BufferedImage result = null;

        if (c != null) {

            Dimension bounds = c.getPreferredSize();
            result = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = result.createGraphics();
            g2d.setClip(new java.awt.Rectangle(c.getSize()));
            g2d.setComposite(AlphaComposite.Clear);
            g2d.fillRect(0, 0, bounds.width, bounds.height);
            g2d.setComposite(AlphaComposite.SrcOver);
            c.paint(g2d);

            g2d.dispose();
        }

        return (result);
    }
}

Related

  1. buildImage(Component c)
  2. componentToImage(Component c)
  3. componentToImage(Component component, int resolution)
  4. doScreenshotToFile(final Component container, final Path filePath, final String imageType)
  5. ensureImageLoaded(Component owner, Image image)