Example usage for java.awt Image getGraphics

List of usage examples for java.awt Image getGraphics

Introduction

In this page you can find the example usage for java.awt Image getGraphics.

Prototype

public abstract Graphics getGraphics();

Source Link

Document

Creates a graphics context for drawing to an off-screen image.

Usage

From source file:ca.sqlpower.wabit.report.ResultSetRendererTest.java

/**
 * Tests calling renderSuccess with an empty result set works without
 * throwing any exceptions.//  w w  w  .  j  av a2  s  . c  o m
 */
public void testRenderSuccessWithEmptyRS() throws Exception {

    ResultSetRenderer renderer = new ResultSetRenderer(query);
    renderer.refresh();

    Image image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    renderer.renderReportContent(g, 1, 1, 1, 1, false, null);
}

From source file:com.openbravo.pos.util.JRPrinterAWT.java

/**
 *
 *///w  w w.  j av a 2  s  .c  o  m
public Image printPageToImage(int pageIndex, float zoom) throws JRException {
    Image pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * zoom) + 1,
            (int) (jasperPrint.getPageHeight() * zoom) + 1, BufferedImage.TYPE_INT_RGB);

    JRGraphics2DExporter exporter = new JRGraphics2DExporter(jasperReportsContext);
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
    exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
    exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, new Float(zoom));
    exporter.exportReport();

    return pageImage;
}

From source file:displayStructureAsPDFTable.java

public void drawStructure(IAtomContainer mol, int cnt) {
    mol = addHeteroHydrogens(mol);//from   w w  w  .  j a v  a  2  s  .  c  o  m

    // do aromaticity detection
    try {
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }

    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        r2dm.setShowAromaticity(true);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);

        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());

    } catch (Exception exc) {
        exc.printStackTrace();
    }

    this.frame.getContentPane().add(this);
    this.frame.pack();

    Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
    try {
        StringBuffer comment = new StringBuffer();

        PdfPCell cell = new PdfPCell();
        Phrase phrase = new Phrase();

        addTitle(mol, phrase);

        if (props) {
            Map<Object, Object> propertyMap = mol.getProperties();
            for (Object key : propertyMap.keySet()) {
                if (key.equals("AllRings"))
                    continue;
                if (key.equals("SmallestRings"))
                    continue;
                if (key.equals(CDKConstants.TITLE))
                    continue;
                addProperty(key, mol, phrase);
            }
        }
        cell.addElement(phrase);
        table.addCell(cell);

        Image awtImage = createImage(this.getSize().width, this.getSize().height);
        Graphics snapGraphics = awtImage.getGraphics();
        paint(snapGraphics);

        com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
        pdfImage.setAbsolutePosition(0, 0);
        table.addCell(pdfImage);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:krasa.cpu.CpuUsagePanel.java

@Override
public void paintComponent(final Graphics g) {
    final boolean pressed = getModel().isPressed();
    final boolean stateChanged = myWasPressed != pressed;
    myWasPressed = pressed;/* w ww.j  a va2s .  c  o  m*/
    Image bufferedImage = myBufferedImage;

    if (bufferedImage == null || stateChanged) {
        final Dimension size = getSize();
        final Insets insets = getInsets();

        bufferedImage = UIUtil.createImage(g, size.width, size.height, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics().create();

        final int max = 100;
        int system = CpuUsageManager.system;
        int process = CpuUsageManager.process;
        final int otherProcesses = system - process;

        final int totalBarLength = size.width - insets.left - insets.right - 3;
        final int processUsageBarLength = totalBarLength * process / max;
        final int otherProcessesUsageBarLength = totalBarLength * otherProcesses / max;
        final int barHeight = Math.max(size.height, getFont().getSize() + 2);
        final int yOffset = (size.height - barHeight) / 2;
        final int xOffset = insets.left;

        // background
        g2.setColor(UIUtil.getPanelBackground());
        g2.fillRect(0, 0, size.width, size.height);

        // gauge (ide)
        g2.setColor(ideColor);
        g2.fillRect(xOffset + 1, yOffset, processUsageBarLength + 1, barHeight);

        // gauge (system)
        g2.setColor(systemColor);
        g2.fillRect(xOffset + processUsageBarLength + 1, yOffset, otherProcessesUsageBarLength + 1, barHeight);

        // label
        g2.setFont(getFont());
        // final String info = CpuUsageBundle.message("cpu.usage.panel.message.text", CpuUsageManager.process,
        // CpuUsageManager.system);
        final String info = fixedLengthString(String.valueOf(process), 3) + "% / "
                + fixedLengthString(String.valueOf(system), 3) + "%";

        final FontMetrics fontMetrics = g.getFontMetrics();
        final int infoWidth = fontMetrics.charsWidth(info.toCharArray(), 0, info.length());
        final int infoHeight = fontMetrics.getAscent();
        UISettings.setupAntialiasing(g2);

        final Color fg = pressed ? UIUtil.getLabelDisabledForeground() : JBColor.foreground();
        g2.setColor(fg);
        g2.drawString(info, xOffset + (totalBarLength - infoWidth) / 2,
                yOffset + infoHeight + (barHeight - infoHeight) / 2 - 1);

        // border
        g2.setStroke(new BasicStroke(1));
        g2.setColor(JBColor.GRAY);
        g2.drawRect(0, 0, size.width - 2, size.height - 1);

        g2.dispose();
        myBufferedImage = bufferedImage;
    }

    draw(g, bufferedImage);
}

From source file:displayStructureAsPDFTable.java

public void drawStructure(IAtomContainer mol, int cnt) {

    // do aromaticity detection
    try {/*w w w . j  a  v  a 2 s .c  o m*/
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }
    mol = addHeteroHydrogens(mol);
    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowAromaticity(true);
        r2dm.setShowAromaticityInCDKStyle(false);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    this.frame.getContentPane().add(this);
    this.frame.pack();

    String filename;
    if (cnt < 10)
        filename = this.odir + "/img00" + cnt + this.suffix;
    else if (cnt < 100)
        filename = this.odir + "/img0" + cnt + this.suffix;
    else
        filename = this.odir + "/img" + cnt + this.suffix;

    if (oformat.equalsIgnoreCase("png") || oformat.equalsIgnoreCase("jpeg")) {
        BufferedImage img;
        try {
            img = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
            //                img = (BufferedImage) createImage(this.getSize().width, this.getSize().height);
            Graphics2D snapGraphics = (Graphics2D) img.getGraphics();
            this.paint(snapGraphics);
            File graphicsFile = new File(filename);
            ImageIO.write(img, oformat, graphicsFile);
        } catch (NullPointerException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else if (oformat.equalsIgnoreCase("pdf")) {
        File file = new File(filename);
        Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
        Document document = new Document(pageSize);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            Image awtImage = createImage(this.getSize().width, this.getSize().height);
            Graphics snapGraphics = awtImage.getGraphics();
            paint(snapGraphics);

            com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
            pdfImage.setAbsolutePosition(0, 0);
            cb.addImage(pdfImage);

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        document.close();
    } else if (oformat.equalsIgnoreCase("svg")) {
        /*
             try {
        SVGWriter cow = new SVGWriter(new FileWriter(filename));
        if (cow != null) {
            cow.writeAtomContainer(mol);
            cow.close();
        }
             } catch (IOException ioe) {
        ioe.printStackTrace();
             } catch (CDKException cdke) {
        cdke.printStackTrace();
             }
        */
    }
}

From source file:net.sf.jasperreports.engine.print.JRPrinterAWT.java

/**
 *
 *//*from  ww w.j a  v  a 2s .  c  om*/
public Image printPageToImage(int pageIndex, float zoom) throws JRException {
    Image pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * zoom) + 1,
            (int) (jasperPrint.getPageHeight() * zoom) + 1, BufferedImage.TYPE_INT_RGB);

    JRGraphics2DExporter exporter = new JRGraphics2DExporter(jasperReportsContext);
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    SimpleGraphics2DExporterOutput output = new SimpleGraphics2DExporterOutput();
    output.setGraphics2D((Graphics2D) pageImage.getGraphics());
    exporter.setExporterOutput(output);
    SimpleGraphics2DReportConfiguration configuration = new SimpleGraphics2DReportConfiguration();
    configuration.setPageIndex(pageIndex);
    configuration.setZoomRatio(zoom);
    exporter.setConfiguration(configuration);
    exporter.exportReport();

    return pageImage;
}

From source file:ScribbleDragAndDrop.java

/**
 * This method implements the DragGestureListener interface. It will be
 * invoked when the DragGestureRecognizer thinks that the user has initiated
 * a drag. If we're not in drawing mode, then this method will try to figure
 * out which Scribble object is being dragged, and will initiate a drag on
 * that object./*from   w  w w.j a  va  2s . co m*/
 */
public void dragGestureRecognized(DragGestureEvent e) {
    // Don't drag if we're not in drag mode
    if (!dragMode)
        return;

    // Figure out where the drag started
    MouseEvent inputEvent = (MouseEvent) e.getTriggerEvent();
    int x = inputEvent.getX();
    int y = inputEvent.getY();

    // Figure out which scribble was clicked on, if any by creating a
    // small rectangle around the point and testing for intersection.
    Rectangle r = new Rectangle(x - LINEWIDTH, y - LINEWIDTH, LINEWIDTH * 2, LINEWIDTH * 2);
    int numScribbles = scribbles.size();
    for (int i = 0; i < numScribbles; i++) { // Loop through the scribbles
        Scribble s = (Scribble) scribbles.get(i);
        if (s.intersects(r)) {
            // The user started the drag on top of this scribble, so
            // start to drag it.

            // First, remember which scribble is being dragged, so we can
            // delete it later (if this is a move rather than a copy)
            beingDragged = s;

            // Next, create a copy that will be the one dragged
            Scribble dragScribble = (Scribble) s.clone();
            // Adjust the origin to the point the user clicked on.
            dragScribble.translate(-x, -y);

            // Choose a cursor based on the type of drag the user initiated
            Cursor cursor;
            switch (e.getDragAction()) {
            case DnDConstants.ACTION_COPY:
                cursor = DragSource.DefaultCopyDrop;
                break;
            case DnDConstants.ACTION_MOVE:
                cursor = DragSource.DefaultMoveDrop;
                break;
            default:
                return; // We only support move and copys
            }

            // Some systems allow us to drag an image along with the
            // cursor. If so, create an image of the scribble to drag
            if (dragSource.isDragImageSupported()) {
                Rectangle scribbleBox = dragScribble.getBounds();
                Image dragImage = this.createImage(scribbleBox.width, scribbleBox.height);
                Graphics2D g = (Graphics2D) dragImage.getGraphics();
                g.setColor(new Color(0, 0, 0, 0)); // transparent background
                g.fillRect(0, 0, scribbleBox.width, scribbleBox.height);
                g.setColor(Color.black);
                g.setStroke(linestyle);
                g.translate(-scribbleBox.x, -scribbleBox.y);
                g.draw(dragScribble);
                Point hotspot = new Point(-scribbleBox.x, -scribbleBox.y);

                // Now start dragging, using the image.
                e.startDrag(cursor, dragImage, hotspot, dragScribble, this);
            } else {
                // Or start the drag without an image
                e.startDrag(cursor, dragScribble, this);
            }
            // After we've started dragging one scribble, stop looking
            return;
        }
    }
}

From source file:net.sf.dynamicreports.jasper.builder.JasperReportBuilder.java

public JasperReportBuilder toImage(JasperImageExporterBuilder imageExporterBuilder) throws DRException {
    Validate.notNull(imageExporterBuilder, "imageExporterBuilder must not be null");

    JasperImageExporter imageExporter = imageExporterBuilder.build();
    JRExporter exporter = new ExporterTransform(imageExporter).transform();

    JasperPrint jasperPrint = toJasperPrint();
    Integer fromPage = null;/*from w w  w .j av a2s .c om*/
    Integer toPage = null;
    float zoom = 1;
    String imageType = imageExporter.getImageType().name().toLowerCase();
    int offsetX = 0;
    int offsetY = 0;
    int pageGap = 0;

    if (imageExporter.getZoom() != null) {
        zoom = imageExporter.getZoom();
    }
    if (imageExporter.getOffsetX() != null) {
        offsetX = imageExporter.getOffsetX();
    }
    if (imageExporter.getOffsetY() != null) {
        offsetY = imageExporter.getOffsetY();
    }
    if (imageExporter.getPageGap() != null) {
        pageGap = imageExporter.getPageGap();
    }

    if (imageExporter.getPageIndex() != null && imageExporter.getPageIndex() >= 0) {
        fromPage = imageExporter.getPageIndex();
        toPage = imageExporter.getPageIndex() + 1;
    } else {
        if (imageExporter.getStartPageIndex() != null) {
            fromPage = imageExporter.getStartPageIndex();
        }
        if (imageExporter.getEndPageIndex() != null) {
            toPage = imageExporter.getEndPageIndex();
        }
    }
    if (fromPage == null) {
        fromPage = 0;
    }
    if (toPage == null) {
        toPage = jasperPrint.getPages().size();
    }

    int pages = toPage - fromPage;

    int pageWidth = (int) (jasperPrint.getPageWidth() * zoom);
    int width = pageWidth * pages + (pages - 1) + offsetX * 2;
    int height = (int) (jasperPrint.getPageHeight() * zoom) + offsetY * 2;
    Image pageImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    int offset = offsetX;
    for (int i = 0; i < pages; i++) {
        try {
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
            exporter.setParameter(JRGraphics2DExporterParameter.OFFSET_X, offset);
            exporter.setParameter(JRGraphics2DExporterParameter.OFFSET_Y, offsetY);
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(fromPage++));
            exporter.exportReport();
            offset += pageWidth + pageGap;
        } catch (JRException e) {
            throw new DRException(e);
        }
    }
    try {
        if (imageExporter.getOutputStream() != null) {
            ImageIO.write((RenderedImage) pageImage, imageType, imageExporter.getOutputStream());
        } else if (imageExporter.getOutputFileName() != null) {
            ImageIO.write((RenderedImage) pageImage, imageType, new File(imageExporter.getOutputFileName()));
        } else if (imageExporter.getOutputFile() != null) {
            ImageIO.write((RenderedImage) pageImage, imageType, imageExporter.getOutputFile());
        } else {
            throw new JasperDesignException("ImageExporter output not supported");
        }
    } catch (IOException e) {
        throw new DRException(e);
    }
    return this;
}

From source file:com.floreantpos.jasperreport.swing.JRViewerPanel.java

protected Image getPageErrorImage() {
    Image image = new BufferedImage((int) (viewerContext.getJasperPrint().getPageWidth() * realZoom) + 1,
            (int) (viewerContext.getJasperPrint().getPageHeight() * realZoom) + 1, BufferedImage.TYPE_INT_RGB);

    Graphics2D grx = (Graphics2D) image.getGraphics();
    AffineTransform transform = new AffineTransform();
    transform.scale(realZoom, realZoom);
    grx.transform(transform);/*  w  w  w  .  j  a  v a2s  .  com*/

    drawPageError(grx);

    return image;
}

From source file:net.sf.jasperreports.swing.JRViewerPanel.java

protected Image getPageErrorImage() {
    PrintPageFormat pageFormat = viewerContext.getPageFormat();
    Image image = new BufferedImage((int) (pageFormat.getPageWidth() * realZoom) + 1,
            (int) (pageFormat.getPageHeight() * realZoom) + 1, BufferedImage.TYPE_INT_RGB);

    AffineTransform transform = new AffineTransform();
    transform.scale(realZoom, realZoom);

    Graphics2D grx = (Graphics2D) image.getGraphics();
    try {/*from w ww .j a  va  2 s  .  c  om*/
        grx.transform(transform);

        drawPageError(grx);
    } finally {
        grx.dispose();
    }

    return image;
}