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.centurylink.mdw.designer.pages.ExportHelper.java

public void printImage(String filename, float scale, CanvasCommon canvas, Dimension graphsize) {
    try {/* w w  w .  j  a v a  2s  .  c om*/
        int h_margin = 72, v_margin = 72;
        BufferedImage image = new BufferedImage(graphsize.width + h_margin, graphsize.height + v_margin,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        if (scale > 0)
            g2.scale(scale, scale);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, image.getWidth(), image.getHeight());
        // canvas.paint(g2);
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        canvas.paintComponent(g2);
        canvas.setBackground(bgsave);
        g2.dispose();
        ImageIO.write(image, "jpeg", new File(filename));
        image = null;
        Runtime r = Runtime.getRuntime();
        r.gc();
    } catch (IOException e) {
        System.err.println(e);
    }
}

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

public Image getThumbNailText(Image img, String text) {
    /*/*from www  .jav a 2  s. c  om*/
     * Create an image containing a thumbnail of the product image,
     * or default image.
     * 
     * Then apply the text of the product name. Use text wrapping.
     * 
     * If the product name is too big for the label, ensure that
     * the first part is displayed.
     */

    img = getThumbNail(img);

    BufferedImage imgtext = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgtext.createGraphics();

    // The text
    // <p style="width: 100px"> DOES NOT WORK PROPERLY.
    // use width= instead.
    String html = "<html><p style=\"text-align:center\" width=\"" + imgtext.getWidth() + "\">"
            + StringEscapeUtils.escapeHtml(text) + "</p>";

    JLabel label = new JLabel(html);
    label.setOpaque(false);
    //label.setText("<html><center>Line1<br>Line2");
    label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
    Dimension d = label.getPreferredSize();
    label.setBounds(0, 0, imgtext.getWidth(), d.height);

    // The background
    Color c1 = new Color(0xff, 0xff, 0xff, 0x40);
    Color c2 = new Color(0xff, 0xff, 0xff, 0xd0);

    //        Point2D center = new Point2D.Float(imgtext.getWidth() / 2, label.getHeight());
    //        float radius = imgtext.getWidth() / 3;
    //        float[] dist = {0.1f, 1.0f};
    //        Color[] colors = {c2, c1};        
    //        Paint gpaint = new RadialGradientPaint(center, radius, dist, colors);
    Paint gpaint = new GradientPaint(new Point(0, 0), c1, new Point(label.getWidth() / 2, 0), c2, true);

    g2d.drawImage(img, 0, 0, null);
    int ypos = imgtext.getHeight() - label.getHeight();
    int ypos_min = -4; // todo: configurable
    if (ypos < ypos_min)
        ypos = ypos_min; // Clamp label
    g2d.translate(0, ypos);
    g2d.setPaint(gpaint);
    g2d.fillRect(0, 0, imgtext.getWidth(), label.getHeight());
    label.paint(g2d);

    g2d.dispose();

    return imgtext;
}

From source file:skoa.helpers.Graficos.java

private BufferedImage convertirTipo(BufferedImage i1, int tipo) {
    BufferedImage res = new BufferedImage(i1.getWidth(), i1.getHeight(), tipo);
    Graphics2D g = res.createGraphics();
    g.drawRenderedImage(i1, null);//from   w  ww.  j  a va2s.  co  m
    g.dispose();
    return res;
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.PeakListChartPanel.java

public void mouseDragged(MouseEvent e) {
    if (mouse_start_point != null && theDocument.size() > 0) {
        if (is_moving) {
            // moving
            double mz_delta = screenToDataX(mouse_start_point.getX() - e.getPoint().getX());
            if (mz_delta > 0.) {
                double old_upper_bound = thePlot.getDomainAxis().getUpperBound();
                double old_lower_bound = thePlot.getDomainAxis().getLowerBound();
                double new_upper_bound = Math.min(old_upper_bound + mz_delta, theDocument.getMaxMZ());
                double new_lower_bound = old_lower_bound + new_upper_bound - old_upper_bound;

                thePlot.getDomainAxis().setRange(new Range(new_lower_bound, new_upper_bound));
            } else {
                double old_upper_bound = thePlot.getDomainAxis().getUpperBound();
                double old_lower_bound = thePlot.getDomainAxis().getLowerBound();
                double new_lower_bound = Math.max(old_lower_bound + mz_delta, theDocument.getMinMZ());
                double new_upper_bound = old_upper_bound + new_lower_bound - old_lower_bound;

                thePlot.getDomainAxis().setRange(new Range(new_lower_bound, new_upper_bound));
            }//  ww w  .  j  av  a  2s. c o m

            mouse_start_point = e.getPoint();
        } else {
            // zooming                
            Graphics2D g2 = (Graphics2D) theChartPanel.getGraphics();
            g2.setXORMode(java.awt.Color.gray);

            // delete old rectangle
            if (zoom_rectangle != null)
                g2.draw(zoom_rectangle);

            // create new rectangle
            double start_x = Math.min(e.getX(), mouse_start_point.getX());
            double end_x = Math.max(e.getX(), mouse_start_point.getX());

            Rectangle2D data_area = theChartPanel.getScreenDataArea((int) start_x,
                    (int) mouse_start_point.getY());
            double xmax = Math.min(end_x, data_area.getMaxX());
            zoom_rectangle = new Rectangle2D.Double(start_x, data_area.getMinY(), xmax - start_x,
                    data_area.getHeight());

            // draw new rectangle
            g2.draw(zoom_rectangle);
            g2.dispose();
        }
    }
}

From source file:de.fhg.igd.mapviewer.waypoints.CustomWaypointPainter.java

/**
 * @see AbstractTileOverlayPainter#repaintTile(int, int, int, int,
 *      PixelConverter, int)//w w  w.  j  ava  2s. c o  m
 */
@Override
public BufferedImage repaintTile(int posX, int posY, int width, int height, PixelConverter converter,
        int zoom) {
    if (renderer == null) {
        return null;
    }

    int overlap = getMaxOverlap();

    // overlap pixel coordinates
    Point topLeftPixel = new Point(Math.max(posX - overlap, 0), Math.max(posY - overlap, 0));
    Point bottomRightPixel = new Point(posX + width + overlap, posY + height + overlap); // TODO
    // check
    // against
    // map
    // size

    // overlap geo positions
    GeoPosition topLeft = converter.pixelToGeo(topLeftPixel, zoom);
    GeoPosition bottomRight = converter.pixelToGeo(bottomRightPixel, zoom);

    // overlap geo positions in RTree CRS
    try {
        BoundingBox tileBounds = createSearchBB(topLeft, bottomRight);

        synchronized (waypoints) {
            Set<W> candidates = waypoints.query(tileBounds, matchTileVerifier);

            if (candidates != null) {
                // sort way-points
                List<W> sorted = new ArrayList<W>(candidates);
                Collections.sort(sorted, paintFirstComparator);

                BufferedImage image = createImage(width, height);
                Graphics2D gfx = image.createGraphics();
                configureGraphics(gfx);

                try {
                    // for each way-point within these bounds
                    for (W w : sorted) {
                        processWaypoint(w, posX, posY, width, height, converter, zoom, gfx);
                    }

                    /*
                     * DEBUG String test = getClass().getSimpleName() +
                     * " - x=" + posX + ", y=" + posY + ": " +
                     * candidates.size() + " WPs"; gfx.setColor(Color.BLUE);
                     * gfx.drawString(test, 4, height - 4);
                     * 
                     * gfx.drawString("minX: " + tileBounds.getMinX(), 4,
                     * height - 84); gfx.drawString("maxX: " +
                     * tileBounds.getMaxX(), 4, height - 64);
                     * gfx.drawString("minY: " + tileBounds.getMinY(), 4,
                     * height - 44); gfx.drawString("maxY: " +
                     * tileBounds.getMaxY(), 4, height - 24);
                     * 
                     * gfx.drawRect(0, 0, width - 1, height - 1);
                     */
                } finally {
                    gfx.dispose();
                }

                return image;
            } else {
                return null;
            }
        }
    } catch (IllegalGeoPositionException e) {
        log.warn("Error painting waypoint tile: " + e.getMessage()); //$NON-NLS-1$
        return null;
    }
}

From source file:com.moviejukebox.plugin.DefaultImagePlugin.java

/**
 * Draw the set logo onto a poster/*from  ww w .java 2  s . c  om*/
 *
 * @param movie the movie to check
 * @param bi the image to draw on
 * @return the new buffered image
 */
private BufferedImage drawSet(Movie movie, BufferedImage bi) {
    try {
        BufferedImage biSet = GraphicTools.loadJPEGImage(getResourcesPath() + FILENAME_SET);

        Graphics2D g2d = bi.createGraphics();
        g2d.drawImage(biSet, bi.getWidth() - biSet.getWidth() - 5, 1, null);
        g2d.dispose();
    } catch (FileNotFoundException ex) {
        LOG.warn(LOG_FAILED_TO_LOAD, FILENAME_SET);
    } catch (IOException error) {
        LOG.warn("Failed drawing set logo to thumbnail for {}", movie.getBaseFilename());
        LOG.warn("Please check that set graphic ({}) is in the resources directory. ", FILENAME_SET,
                error.getMessage());
    }

    return bi;
}

From source file:coolmap.canvas.datarenderer.renderer.impl.NumberToBoxPlot.java

private void updateLegend() {

    int width = DEFAULT_LEGEND_WIDTH;
    int height = DEFAULT_LEGENT_HEIGHT;
    legend = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    Graphics2D g = (Graphics2D) legend.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setPaint(UI.colorBlack2);//from   w  ww .j  av a2s. c o  m
    g.fillRoundRect(0, 0, width, height - 12, 5, 5);

    g.setColor(barColorBelow);
    int boxNum = 10;
    g.setStroke(UI.stroke1_5);

    double value;
    for (int i = 0; i < boxNum; i++) {
        value = _minValue + (_maxValue - _minValue) / boxNum * i;

        if (value > disectBound) {
            g.setColor(barColorNormal);
        }

        int h = (height - 12) / boxNum * i;
        g.drawLine(i * width / boxNum, height - 12 - h, (i + 1) * width / boxNum, height - 12 - h);

    }

    g.setColor(Color.BLACK);
    g.setFont(UI.fontMono.deriveFont(10f));
    DecimalFormat format = new DecimalFormat("#.##");
    g.drawString(format.format(_minValue), 2, 23);

    g.setColor(Color.BLACK);
    String maxString = format.format(_maxValue);
    int swidth = g.getFontMetrics().stringWidth(maxString);
    g.drawString(maxString, width - 2 - swidth, 23);
    g.dispose();
}

From source file:com.moviejukebox.plugin.DefaultImagePlugin.java

/**
 * Draw the SubTitle logo on the image//from  ww w  .  ja  v a  2 s. c om
 *
 * @param movie
 * @param bi
 * @return
 */
private BufferedImage drawSubTitle(Movie movie, BufferedImage bi) {
    // If the doesn't have subtitles, then quit
    if (StringTools.isNotValidString(movie.getSubtitles()) || "NO".equalsIgnoreCase(movie.getSubtitles())) {
        return bi;
    }

    File logoFile = new File(getResourcesPath() + FILENAME_SUBTITLE);

    if (!logoFile.exists()) {
        LOG.debug("Missing SubTitle logo ({}) unable to draw logo", FILENAME_SUBTITLE);
        return bi;
    }

    try {
        BufferedImage biSubTitle = GraphicTools.loadJPEGImage(logoFile);
        Graphics2D g2d = bi.createGraphics();
        g2d.drawImage(biSubTitle, bi.getWidth() - biSubTitle.getWidth() - 5, 5, null);
        g2d.dispose();
    } catch (FileNotFoundException ex) {
        LOG.warn(LOG_FAILED_TO_LOAD, logoFile);
    } catch (IOException ex) {
        LOG.warn(
                "Failed drawing SubTitle logo to thumbnail file: Please check that {} is in the resources directory.",
                FILENAME_SUBTITLE);
    }

    return bi;
}

From source file:org.fhcrc.cpl.viewer.quant.gui.PanelWithSpectrumChart.java

License:asdf

/**
 *
 * @param imageWidthEachScan/*ww  w .  jav  a  2s .  c  o m*/
 * @param imageHeightEachScan
 * @param maxTotalImageHeight a hard boundary on the total image height.  If imageHeightEachScan is too big,
 * given the total number of charts and this arg, it gets knocked down
 * @param outputFile
 * @throws java.io.IOException
 */
public void savePerScanSpectraImage(int imageWidthEachScan, int imageHeightEachScan, int maxTotalImageHeight,
        File outputFile) throws IOException {
    int numCharts = scanLineChartMap.size();

    int widthPaddingForLabels = 50;

    imageHeightEachScan = Math.min(imageHeightEachScan, maxTotalImageHeight / numCharts);

    List<Integer> allScanNumbers = new ArrayList<Integer>(scanLineChartMap.keySet());
    Collections.sort(allScanNumbers);
    List<PanelWithChart> allCharts = new ArrayList<PanelWithChart>();

    for (int scanNumber : allScanNumbers) {
        PanelWithLineChart scanChart = scanLineChartMap.get(scanNumber);
        allCharts.add(scanChart);
        scanChart.setSize(imageWidthEachScan - widthPaddingForLabels, imageHeightEachScan);
    }

    BufferedImage perScanChartImage = MultiChartDisplayPanel.createImageForAllCharts(allCharts);

    BufferedImage perScanChartImageWithLabels = new BufferedImage(imageWidthEachScan,
            perScanChartImage.getHeight(), BufferedImage.TYPE_INT_RGB);

    Graphics2D g = perScanChartImageWithLabels.createGraphics();
    g.drawImage(perScanChartImage, widthPaddingForLabels, 0, null);
    g.setPaint(Color.WHITE);
    g.drawRect(0, 0, widthPaddingForLabels, perScanChartImage.getHeight());

    for (int i = 0; i < allCharts.size(); i++) {
        int scanNumber = allScanNumbers.get(i);

        int chartTop = i * imageHeightEachScan;
        int chartMiddle = chartTop + (imageHeightEachScan / 2);

        if (lightFirstScanLine > 0 && lightLastScanLine > 0) {
            if (scanNumber >= lightFirstScanLine && scanNumber <= lightLastScanLine)
                g.setPaint(Color.GREEN);
            else
                g.setPaint(Color.RED);
        } else
            g.setPaint(Color.BLACK);

        g.drawString("" + scanNumber, 5, chartMiddle);
    }
    g.dispose();

    ImageIO.write(perScanChartImageWithLabels, "png", outputFile);
}

From source file:org.gumtree.vis.awt.CompositePanel.java

@Override
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    if (pageIndex != 0) {
        return NO_SUCH_PAGE;
    }/*from w w w.ja v  a2s .  c o  m*/
    Graphics2D g2 = (Graphics2D) g;
    double x = pf.getImageableX();
    double y = pf.getImageableY();
    double w = pf.getImageableWidth();
    double h = pf.getImageableHeight();
    double screenWidth = getWidth();
    double screenHeight = getHeight();
    double widthRatio = w / screenWidth;
    double heightRatio = h / screenHeight;
    double overallRatio = 1;
    overallRatio = widthRatio < heightRatio ? widthRatio : heightRatio;
    //        Rectangle2D printArea = new Rectangle2D.Double(x, y, screenWidth * overallRatio, 
    //              screenHeight * overallRatio);
    BufferedImage image = getImage();
    g2.drawImage(image, (int) x, (int) y, (int) (screenWidth * overallRatio),
            (int) (screenHeight * overallRatio), null);
    //        draw(g2, printArea, x, y);
    g2.dispose();
    return PAGE_EXISTS;

    //        XYPlot plot = (XYPlot) getChart().getPlot();
    //        Font domainFont = plot.getDomainAxis().getLabelFont();
    //        int domainSize = domainFont.getSize();
    //        Font rangeFont = plot.getRangeAxis().getLabelFont();
    //        int rangeSize = rangeFont.getSize();
    //        Font titleFont = getChart().getTitle().getFont();
    //        int titleSize = titleFont.getSize();
    //        Font domainScaleFont = plot.getDomainAxis().getTickLabelFont();
    //        int domainScaleSize = domainScaleFont.getSize();
    //        Font rangeScaleFont = plot.getRangeAxis().getTickLabelFont();
    //        int rangeScaleSize = rangeScaleFont.getSize();
    //        plot.getDomainAxis().setLabelFont(domainFont.deriveFont(
    //              (float) (domainSize * overallRatio)));
    //        plot.getRangeAxis().setLabelFont(rangeFont.deriveFont(
    //              (float) (rangeSize * overallRatio)));
    //        getChart().getTitle().setFont(titleFont.deriveFont(
    //              (float) (titleSize * overallRatio)));
    //        plot.getDomainAxis().setTickLabelFont(domainScaleFont.deriveFont(
    //              (float) (domainScaleSize * overallRatio)));
    //        plot.getRangeAxis().setTickLabelFont(rangeScaleFont.deriveFont(
    //              (float) (rangeScaleSize * overallRatio)));
    //        
    //        Rectangle2D chartArea = (Rectangle2D) printArea.clone();
    //        getChart().getPadding().trim(chartArea);
    //        AxisUtilities.trimTitle(chartArea, g2, getChart().getTitle(), getChart().getTitle().getPosition());
    //        
    //        Axis scaleAxis = null;
    //        Font scaleAxisFont = null;
    //        int scaleAxisFontSize = 0;
    //        for (Object object : getChart().getSubtitles()) {
    //           Title title = (Title) object;
    //           if (title instanceof PaintScaleLegend) {
    //              scaleAxis = ((PaintScaleLegend) title).getAxis();
    //              scaleAxisFont = scaleAxis.getTickLabelFont();
    //              scaleAxisFontSize = scaleAxisFont.getSize();
    //              scaleAxis.setTickLabelFont(scaleAxisFont.deriveFont(
    //                    (float) (scaleAxisFontSize * overallRatio)));
    //           }
    //           AxisUtilities.trimTitle(chartArea, g2, title, title.getPosition());
    //        }
    //        AxisSpace axisSpace = AxisUtilities.calculateAxisSpace(
    //              getChart().getXYPlot(), g2, chartArea);
    //        Rectangle2D dataArea = axisSpace.shrink(chartArea, null);
    //        getChart().getXYPlot().getInsets().trim(dataArea);
    //        getChart().getXYPlot().getAxisOffset().trim(dataArea);
    //        
    ////        Rectangle2D screenArea = getScreenDataArea();
    ////        Rectangle2D visibleArea = getVisibleRect();
    ////        Rectangle2D printScreenArea = new Rectangle2D.Double(screenArea.getMinX() * overallRatio + x, 
    ////              screenArea.getMinY() * overallRatio + y, 
    ////              printArea.getWidth() - visibleArea.getWidth() + screenArea.getWidth(), 
    ////              printArea.getHeight() - visibleArea.getHeight() + screenArea.getHeight());
    //
    //        getChart().draw(g2, printArea, getAnchor(), null);
    //        ChartMaskingUtilities.drawMasks(g2, dataArea, 
    //              getMasks(), null, getChart(), overallRatio);
    //        plot.getDomainAxis().setLabelFont(domainFont);
    //        plot.getRangeAxis().setLabelFont(rangeFont);
    //        getChart().getTitle().setFont(titleFont);
    //        plot.getDomainAxis().setTickLabelFont(domainScaleFont);
    //        plot.getRangeAxis().setTickLabelFont(rangeScaleFont);
    //        if (scaleAxis != null) {
    //           scaleAxis.setTickLabelFont(scaleAxisFont);
    //        }
    //        return PAGE_EXISTS;
}