Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:Main.java

/**
 * This method returns a buffered image with the contents of an image
 * This snippet was taken from: http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html
 * @param image/*  www  .j av  a  2  s .  c o  m*/
 * @return The buffered image
 */
public static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }

    // This code ensures that all the pixels in the image are loaded
    image = new ImageIcon(image).getImage();

    // Determine if the image has transparent pixels; for this method's
    // implementation, see e661 Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the new buffered image
        int transparency = Transparency.OPAQUE;
        if (hasAlpha) {
            transparency = Transparency.BITMASK;
        }

        // Create the buffered image
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }

    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        if (hasAlpha) {
            type = BufferedImage.TYPE_INT_ARGB;
        }
        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    }

    // Copy image to buffered image
    Graphics g = bimage.createGraphics();

    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bimage;
}

From source file:com.igormaznitsa.jhexed.values.HexSVGImageValue.java

@Override
public BufferedImage makeIcon(final int width, final int height, final Path2D shape, final boolean allowAlpha) {
    try {//from   ww w.j  a v a 2  s  .  c  o m
        final BufferedImage img = this.image.rasterize(width, height, BufferedImage.TYPE_INT_ARGB);
        if (shape == null) {
            return img;
        } else {
            final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            final Graphics2D g = result.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                    RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g.setClip(makeTransformedPathForSize(width, height, shape));
            g.drawImage(img, 0, 0, null);
            g.dispose();
            return result;
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.github.andreax79.meca.Main.java

public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern,
        int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException {
    Rule rule = new Rule(ruleNumber);
    Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111
    Stats stats = new Stats();

    FileOutputStream finalImage = null;
    Graphics2D g = null;//from   w ww  .ja v  a2 s . c  o m
    BufferedImage img = null;

    if (output != Output.noOutput) {
        String fileName = "rule" + ruleNumber;
        // pattern
        if (pattern != null)
            fileName += pattern;
        // alpha
        if (alpha > 0)
            fileName += String.format("_a%02d", (int) (alpha * 100));
        // updatePattern
        if (updatePattern != UpdatePattern.synchronous)
            fileName += "-" + updatePattern;
        fileName += ".jpeg";

        File file = new File(fileName);
        finalImage = new FileOutputStream(file);

        int width = (int) (cellSize * (size + 1) * (output == Output.all ? 1.25 : 1));
        int height = cellSize * (steps + 1);
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g = img.createGraphics();
        g.setBackground(Color.white);
        g.clearRect(0, 0, width, height);
        g.setColor(Color.black);
    }

    int startMeansFromStep = 50;
    List<Double> densities = new LinkedList<Double>();
    double totalDensities = 0;

    double prevValue = 0;
    double prevDelta = 0;
    double prevOnes = 0;
    double prevOnesDelta = 0;

    for (int t = 0; t < steps; t++) {
        if (t >= startMeansFromStep) {
            double density = row.getDensity();
            densities.add(density);
            totalDensities += density;
        }
        // System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes());
        if (output != Output.noOutput) {
            for (int j = 0; j < row.getSize(); j++) {

                switch (colorScheme) {
                case noColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(Color.black);
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                case omegaColor:
                    g.setColor(row.getCell(j).getOmegaColor());
                    g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    break;
                case activationColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(row.getCell(j).getColor());
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                }
            }

            if (output == Output.all) {
                double value = row.getValue();
                double delta = Math.abs(value - prevValue);
                double ones = row.getOnes();
                double onesDelta = Math.abs(ones - prevOnes);
                if (t > 0) {
                    g.setColor(Color.red);
                    g.drawLine((int) (prevValue * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (value * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    g.setColor(Color.blue);
                    g.drawLine((int) (prevOnes * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (ones * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    if (t > 1) {
                        g.setColor(Color.orange);
                        g.drawLine((int) (prevDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (delta * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize));
                        g.setColor(Color.cyan);
                        g.drawLine((int) (prevOnesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (onesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) (t * cellSize));
                    }
                }
                prevValue = value;
                prevDelta = delta;
                prevOnes = ones;
                prevOnesDelta = onesDelta;
            }
        }

        row = new Row(row);
    }

    double means = totalDensities / densities.size();
    double var = 0;
    for (double density : densities)
        var += Math.pow(density - means, 2);
    var = var / densities.size();
    System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern
            + " Alpha: " + String.format("%.3f", alpha) + " Means: " + String.format("%.6f", means)
            + " Variance: " + String.format("%.6f", var));
    stats.setMeans(means);
    stats.setVariance(var);

    if (output != Output.noOutput) {
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
        param.setQuality(1.0f, true);
        encoder.encode(img, param);
        finalImage.flush();
        finalImage.close();
    }

    return stats;
}

From source file:gui.images.CodebookVectorProfilePanel.java

/**
 * Generate a BufferedImage that would correspond to a JPanel. Images are
 * faster to show than interactive components if many components need to be
 * presented./*w  w  w . j  a  v  a2s. c  o m*/
 *
 * @param panel JPanel object.
 * @return BufferedImage of how the content in the provided panel would be
 * rendered.
 */
public BufferedImage createImage(JPanel panel) {
    int width = panel.getSize().width;
    int height = panel.getSize().height;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    panel.paint(g);
    return bi;
}

From source file:probe.com.model.util.vaadintoimageutil.Convertor.java

public String toImage(int height, int width, JComponent component) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    component.paint(graphics);/*from  ww w.j  av a  2  s . c o  m*/
    //        super.paint(graphics);
    byte[] imageData = null;

    try {

        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;

}

From source file:com.us.servlet.AuthCode.java

protected void service(HttpServletRequest request, HttpServletResponse response) {
    final CodeAuth bean = AppHelper.CODE_AUTH;
    int width = NumberUtils.toInt(request.getParameter("width"), bean.getWidth());
    int height = NumberUtils.toInt(request.getParameter("height"), bean.getHeight());
    int x = width / (bean.getLength() + 1);
    int codeY = height - 4;
    int fontHeight = height - 2;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = image.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    if (StringUtil.hasText(request.getParameter("bgcolor"))) {
        graphics.setBackground(ColorHelper.hex2RGB(request.getParameter("bgcolor")));
    }//  w  w w.  j  a v a2 s .  c o  m
    graphics.fillRect(0, 0, width, height);
    graphics.setFont(new Font(bean.getFont(), Font.BOLD, fontHeight));
    graphics.drawRect(0, 0, width - 1, height - 1);
    // 
    if (bean.isBreakLine()) {
        for (int i = 0; i < 15; i++) {
            int x1 = RandomUtils.nextInt(width);
            int y1 = RandomUtils.nextInt(height);
            int x2 = RandomUtils.nextInt(12);
            int y2 = RandomUtils.nextInt(12);
            graphics.drawLine(x1, y1, x + x2, y1 + y2);
        }
    }
    char[] CHARSET_AREA = null;
    if (bean.getType().charAt(0) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS);
    }
    if (bean.getType().charAt(1) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER);
    }
    if (bean.getType().charAt(2) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS);
    }
    StringBuilder randomCode = new StringBuilder();
    for (int i = 0; i < bean.getLength(); i++) {
        String rand = String.valueOf(CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)]);
        graphics.setColor(ColorHelper.color(RandomUtils.nextInt(255), RandomUtils.nextInt(255),
                RandomUtils.nextInt(255)));
        graphics.drawString(rand, (i + 1) * x, codeY);
        randomCode.append(rand);
    }
    HttpSession session = request.getSession();
    session.setAttribute(bean.getSessionKey(), randomCode.toString());
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/png");
    try {
        // Servlet?
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "png", sos);
        sos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Rescales using predefined min,max intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16//  ww w.j  ava  2  s  .  c o  m
 * @return
 */
public static BufferedImage convertTo8bit(BufferedImage bi16, int min, int max) {
    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, new int[] { min }, new int[] { max });
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else if (bi16.getSampleModel().getNumBands() == 3) {
        throw new IllegalArgumentException("only grayscale images supported");
    } else {
        throw new IllegalArgumentException(
                "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has "
                        + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}

From source file:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.heatmap.HeatMapImgGenerator.java

public String generateHeatmap(String[] rows, String[] columns, String[][] data) {

    JPanel heatmapPanelLayout = new JPanel();
    heatmapPanelLayout.setLayout(null);//from www.ja  v a  2s.  co m
    heatmapPanelLayout.setVisible(true);

    int width = (columns.length + 1) * 50;
    int height = (rows.length + 1) * 50;
    heatmapPanelLayout.setSize(width, height);
    JPanel cornerCell = initCell("#ffffff", 0, 0);
    int x = 50;
    int y = 0;
    heatmapPanelLayout.add(cornerCell);

    for (String headerCell : columns) {
        JPanel cell = initCell(headerCell, x, y);
        x += 50;
        heatmapPanelLayout.add(cell);

    }
    y = 50;
    for (String headerCell : rows) {
        JPanel cell = initCell(headerCell, 0, y);
        y += 50;
        heatmapPanelLayout.add(cell);

    }
    x = 50;
    y = 50;
    for (String[] row : data) {
        for (String color : row) {
            JPanel cell = initCell(color, x, y);
            heatmapPanelLayout.add(cell);
            x += 50;
        }
        x = 50;
        y += 50;
    }

    BufferedImage image = new BufferedImage(width + 10, height + 10, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    graphics.setBackground(Color.WHITE);
    heatmapPanelLayout.paint(graphics);
    byte[] imageData = null;

    try {

        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, new Float(0.084666f));
        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;

}

From source file:ImageOps.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Create a BufferedImage big enough to hold the Image loaded
    // in the constructor. Then copy that image into the new
    // BufferedImage object so that we can process it.
    BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D ig = bimage.createGraphics();
    ig.drawImage(image, 0, 0, this); // copy the image

    // Set some default graphics attributes
    g.setFont(new Font("SansSerif", Font.BOLD, 12)); // 12pt bold text
    g.setColor(Color.green); // Draw in green
    g.translate(10, 10); // Set some margins

    // Loop through the filters
    for (int i = 0; i < filters.length; i++) {
        // If the filter is null, draw the original image, otherwise,
        // draw the image as processed by the filter
        if (filters[i] == null)
            g.drawImage(bimage, 0, 0, this);
        else//w ww .j ava  2  s . com
            g.drawImage(filters[i].filter(bimage, null), 0, 0, this);
        g.drawString(filterNames[i], 0, 205); // Label the image
        g.translate(137, 0); // Move over
        if (i % 4 == 3)
            g.translate(-137 * 4, 215); // Move down after 4
    }
}

From source file:bachelorthesis.ocr.domain.DomainFacade.java

private Captcha createCaptcha(String buildString, int width, int height) throws RuntimeException {
    try {/*from  www  .  ja  v  a  2s .  c o m*/
        CaptchaBuilder captchaBuilder = new CaptchaBuilder(40, 50, buildString);
        Captcha c = captchaBuilder.buildCaptcha();
        BufferedImage img = c.getImage();

        // check if size == the default size (40*50) if not scale
        if (width != 40 || height != 50) {
            BufferedImage resized = new BufferedImage(width, height, img.getType());
            Graphics2D g = resized.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(img, 0, 0, width, height, 0, 0, img.getWidth(), img.getHeight(), null);
            g.dispose();

            //build new CAPTCHA WITH THE NEW IMAGE SIZE
            c = new Captcha(c.getBuildSequence(), c.getAnswer(), c.isCaseSensative(), img, new Date());
        }

        return c;

    } catch (ParseException ex) {
        Logger.getLogger(DomainFacade.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("error creating CAPTCHA");
    }
}