Example usage for java.awt Graphics2D dispose

List of usage examples for java.awt Graphics2D dispose

Introduction

In this page you can find the example usage for java.awt Graphics2D dispose.

Prototype

public abstract void dispose();

Source Link

Document

Disposes of this graphics context and releases any system resources that it is using.

Usage

From source file:com.ables.pix.utility.PictureOps.java

public static BufferedImage tilt(BufferedImage image, double rotation) {
    double sin = Math.abs(Math.sin(getAngle()));
    double cos = Math.abs(Math.cos(getAngle()));
    int w = image.getWidth(), h = image.getHeight();

    int neww = (int) Math.floor(w * cos + sin * h), newh = (int) Math.floor(h * cos + sin * w);
    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage rotated = gc.createCompatibleImage(neww, newh);
    Graphics2D g = rotated.createGraphics();
    g.translate((neww - w) / 2, (newh - h / 2));
    g.rotate(getAngle(), w / 2, h / 2);/*from   w  w w  . j  a v  a  2 s  .c om*/
    g.drawRenderedImage(image, null);
    g.dispose();
    return rotated;
}

From source file:WeeklyReport.WeeklyPDF.java

public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) {
    PdfWriter writer = null;//from  ww w. j a  va 2s  .  c  om
    Document document = new Document();
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        document.add(new Paragraph("Here is the recommendation"));
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(5, -100, width, height);
        chart.draw(graphics2d, rectangle2d);
        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (FileNotFoundException | DocumentException ex) {
        ex.getMessage();
    }
    document.close();
}

From source file:Main.java

public static TexturePaint createCheckerTexture(int cs, Color color) {
    int size = cs * cs;
    BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = img.createGraphics();
    g2.setPaint(color);//from  w  ww .j  a va 2  s .co  m
    g2.fillRect(0, 0, size, size);
    for (int i = 0; i * cs < size; i++) {
        for (int j = 0; j * cs < size; j++) {
            if ((i + j) % 2 == 0) {
                g2.fillRect(i * cs, j * cs, cs, cs);
            }
        }
    }
    g2.dispose();
    return new TexturePaint(img, new Rectangle(0, 0, size, size));
}

From source file:Transparency.java

public static BufferedImage makeImageTranslucent(BufferedImage source, double alpha) {
    BufferedImage target = new BufferedImage(source.getWidth(), source.getHeight(),
            java.awt.Transparency.TRANSLUCENT);
    // Get the images graphics
    Graphics2D g = target.createGraphics();
    // Set the Graphics composite to Alpha
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) alpha));
    // Draw the image into the prepared reciver image
    g.drawImage(source, null, 0, 0);//  w w w. j  a v a2  s  . c  o  m
    // let go of all system resources in this Graphics
    g.dispose();
    // Return the image
    return target;
}

From source file:com.vaadin.testbench.screenshot.ImageUtil.java

/**
 * Clones the given BufferedImage//from w ww . j  a v  a  2  s.com
 * 
 * @param sourceImage
 *            The image to copy
 * @return A copy of sourceImage
 */
public static BufferedImage cloneImage(BufferedImage sourceImage) {
    // This method could likely be optimized but the gain is probably
    // small
    final int w = sourceImage.getWidth();
    final int h = sourceImage.getHeight();

    BufferedImage newImage = new BufferedImage(w, h, TYPE_INT_RGB);

    Graphics2D g = (Graphics2D) newImage.getGraphics();
    g.drawImage(sourceImage, 0, 0, w, h, null);
    g.dispose();

    return newImage;
}

From source file:Utils.java

/** 
 * Renders multiple paragraphs of text in an array to an image (created and returned). 
 *
 * @param font The font to use/*from   w  w  w. j a va2  s .  c o  m*/
 * @param textColor The color of the text
 * @param text The message in an array of strings (one paragraph in each
 * @param width The width the text should be limited to
 * @return An image with the text rendered into it
 */
public static BufferedImage renderTextToImage(Font font, Color textColor, String text[], int width) {
    LinkedList<BufferedImage> images = new LinkedList<BufferedImage>();

    int totalHeight = 0;

    for (String paragraph : text) {
        BufferedImage paraImage = renderTextToImage(font, textColor, paragraph, width);
        totalHeight += paraImage.getHeight();
        images.add(paraImage);
    }

    BufferedImage image = createCompatibleImage(width, totalHeight);
    Graphics2D graphics = (Graphics2D) image.createGraphics();

    int y = 0;

    for (BufferedImage paraImage : images) {
        graphics.drawImage(paraImage, 0, y, null);
        y += paraImage.getHeight();
    }

    graphics.dispose();
    return image;
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectEditController.java

private static BufferedImage resize(BufferedImage image, int width, int height) {
    BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = resizedImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();
    return resizedImage;
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight,
        boolean preserveAlpha) {
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }/*from w  w  w  .  j a v  a2  s  .c  o m*/
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    return scaledBI;
}

From source file:at.granul.mason.collector.ChartFileScalarDataWriter.java

public static void exportGraph(XYChartGenerator chart, String prefix, int width, int height) {
    try {//from   ww w .  j  a  va2 s .  com
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".pdf")));

        document.addAuthor("MASON");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        //PdfTemplate tp = cb.createTemplate(width, height);

        //Write the chart with all datasets
        chart.addLegend();
        /*LegendTitle title = new LegendTitle(chart.getChart().getPlot());
        title.setLegendItemGraphicPadding(new org.jfree.ui.RectangleInsets(0,8,0,4));
        chart.addLegend(title);*/
        LegendTitle legendTitle = chart.getChart().getLegend();
        legendTitle.setPosition(RectangleEdge.BOTTOM);

        Graphics2D g2 = cb.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
        chart.getChart().draw(g2, rectangle2D);
        g2.dispose();

        //PNG Output
        ChartUtilities.saveChartAsJPEG(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".png"),
                chart.getChart(), width, height);

        chart.getChart().removeLegend();
        //tp = cb.createTemplate(width, height);

        //All invisible
        final XYItemRenderer renderer = chart.getChartPanel().getChart().getXYPlot().getRenderer();
        for (int a = 0; a < chart.getSeriesCount(); a++) {
            renderer.setSeriesVisible(a, false);
        }

        final Dataset seriesDataset = chart.getSeriesDataset();
        XYSeriesCollection series = ((XYSeriesCollection) seriesDataset);
        for (int a = 0; a < chart.getSeriesCount(); a++) {
            renderer.setSeriesVisible(a, true);
            final String seriesName = series.getSeries(a).getKey() + "";
            chart.setYAxisLabel(seriesName);
            document.newPage();
            g2 = cb.createGraphics(width, height * (a + 2), new DefaultFontMapper());
            g2.translate(0, height * (a + 1));
            chart.getChart().draw(g2, rectangle2D);
            g2.dispose();

            //PNG Output
            ChartUtilities.saveChartAsJPEG(
                    new File(prefix + "_" + seriesName + DataWriter.DF.format(new Date()) + ".png"),
                    chart.getChart(), width, height);

            renderer.setSeriesVisible(a, false);
        }
        //cb.addTemplate(tp, 0, 0);

        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {//from   www  . ja  v  a 2  s.  c o m
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

        DecimalFormat df = new DecimalFormat("#.###");

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}