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:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

/**
  * @param question/*  w w w  .jav a2s. c  o m*/
  *            the question text
  * @param choices
  *            the text for the choices
  * @param values
  *            the count of answers for each choice (same order as choices)
  * @param responseCount
  *            the number of responses to the question
  * @param showPercentages
  *            if true then show the percentages
  * @param answersAndMean
  *            the text which will be displayed above the chart (normally the answers count and
  *            mean)
  * @param lastElementIsHeader
  *            If the last element was a header, the extra spacing paragraph is not needed.
  */
public void addLikertResponse(String question, String[] choices, int[] values, int responseCount,
        boolean showPercentages, String answersAndMean, boolean lastElementIsHeader) {
    ArrayList<Element> myElements = new ArrayList<>();

    try {
        if (!lastElementIsHeader) {
            Paragraph emptyPara = new Paragraph(" ");
            this.addElementWithJump(emptyPara, false);
        }

        Paragraph myPara = new Paragraph(question, questionTextFont);
        myPara.setSpacingAfter(SPACING_AFTER_HEADER);
        myElements.add(myPara);

        EvalLikertChartBuilder chartBuilder = new EvalLikertChartBuilder();
        chartBuilder.setValues(values);
        chartBuilder.setResponses(choices);
        chartBuilder.setShowPercentages(showPercentages);
        chartBuilder.setResponseCount(responseCount);
        JFreeChart chart = chartBuilder.makeLikertChart();

        /* The height is going to be based off the number of choices */
        int height = 15 * choices.length;

        PdfContentByte cb = pdfWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(200, height);
        Graphics2D g2d = tp.createGraphics(200, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, 200, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        Image image = Image.getInstance(tp);

        // put image in the document
        myElements.add(image);

        if (answersAndMean != null) {
            Paragraph header = new Paragraph(answersAndMean, paragraphFont);
            header.setSpacingAfter(SPACING_BETWEEN_LIST_ITEMS);
            myElements.add(header);
        }

        this.addElementArrayWithJump(myElements);
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        LOG.warn(e);
    }
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

private BufferedImage toBufferedCompanyImage(Image image) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = bufferedImage.createGraphics();
    //       java.awt.Color transparent = new java.awt.Color(255, 255, 255, 1);
    //                g.setColor(transparent);
    //                int rule = java.awt.AlphaComposite.SRC_OVER;
    //                        
    //                java.awt.AlphaComposite ac = java.awt.AlphaComposite.getInstance(rule,1);
    //                g.setComposite(ac);
    //      g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
    g.drawImage(image, 0, 0, null);/*  w  w  w.  j  ava2  s  . c o m*/
    g.dispose();

    return bufferedImage;
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public BufferedImage resize(BufferedImage image, int width, int height) {
    int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();
    return resizedImage;
}

From source file:de.fhg.igd.mapviewer.server.wms.overlay.WMSTileOverlay.java

/**
 * @see AbstractTileOverlayPainter#repaintTile(int, int, int, int,
 *      PixelConverter, int)/*from  w w  w .  j  a v a2 s . c  o  m*/
 */
@Override
public BufferedImage repaintTile(int posX, int posY, int width, int height, PixelConverter converter,
        int zoom) {
    // the first converter isn't regarded as a new converter because it's
    // always the empty map
    boolean isNewConverter = lastConverter != null && !converter.equals(lastConverter);
    lastConverter = converter;

    if (!converter.supportsBoundingBoxes()) {
        if (isNewConverter) {
            handleError(Messages.WMSTileOverlay_0 + configuration.getName() + Messages.WMSTileOverlay_1);
        }
        return null;
    }

    synchronized (this) {
        if (capabilities == null) {
            try {
                capabilities = WMSUtil.getCapabilities(configuration.getBaseUrl());
            } catch (WMSCapabilitiesException e) {
                log.error("Error getting WMS capabilities"); //$NON-NLS-1$
            }
        }
    }

    if (capabilities != null) {
        int mapEpsg = converter.getMapEpsg();

        WMSBounds box;
        synchronized (this) {
            if (capabilities.getSupportedSRS().contains("EPSG:" + mapEpsg)) { //$NON-NLS-1$
                // same SRS supported
            } else {
                // SRS not supported
                if (isNewConverter) {
                    StringBuilder message = new StringBuilder();
                    message.append(Messages.WMSTileOverlay_2);
                    message.append(configuration.getName());
                    message.append(Messages.WMSTileOverlay_3);
                    boolean init = true;
                    for (String srs : capabilities.getSupportedSRS()) {
                        if (init) {
                            init = false;
                        } else {
                            message.append(", "); //$NON-NLS-1$
                        }
                        message.append(srs);
                    }
                    handleError(message.toString());
                }
                return null;
            }

            box = WMSUtil.getBoundingBox(capabilities, mapEpsg);
        }

        String srs = box.getSRS();

        if (srs.startsWith("EPSG:")) { //$NON-NLS-1$
            // determine format
            String format = null;
            Iterator<String> itFormat = supportedFormats.iterator();
            synchronized (this) {
                while (format == null && itFormat.hasNext()) {
                    String supp = itFormat.next();
                    if (capabilities.getFormats().contains(supp)) {
                        format = supp;
                    }
                }
            }
            if (format == null) {
                // no compatible format
                return null;
            }

            try {
                // check if tile lies within the bounding box
                int epsg = Integer.parseInt(srs.substring(5));

                GeoPosition topLeft = converter.pixelToGeo(new Point(posX, posY), zoom);
                GeoPosition bottomRight = converter.pixelToGeo(new Point(posX + width, posY + height), zoom);

                // WMS bounding box
                BoundingBox wms = new BoundingBox(box.getMinX(), box.getMinY(), -1, box.getMaxX(),
                        box.getMaxY(), 1);

                GeoConverter geotools = GeotoolsConverter.getInstance();
                GeoPosition bbTopLeft = geotools.convert(topLeft, epsg);
                GeoPosition bbBottomRight = geotools.convert(bottomRight, epsg);

                double minX = Math.min(bbTopLeft.getX(), bbBottomRight.getX());
                double minY = Math.min(bbTopLeft.getY(), bbBottomRight.getY());
                double maxX = Math.max(bbTopLeft.getX(), bbBottomRight.getX());
                double maxY = Math.max(bbTopLeft.getY(), bbBottomRight.getY());

                BoundingBox tile = new BoundingBox(minX, minY, -1, maxX, maxY, 1);

                // check if bounding box and tile overlap
                if (wms.intersectsOrCovers(tile) || tile.covers(wms)) {
                    WMSBounds bounds;
                    if (epsg == mapEpsg) {
                        bounds = new WMSBounds(srs, minX, minY, maxX, maxY);
                    } else {
                        // determine bounds for request
                        minX = Math.min(topLeft.getX(), bottomRight.getX());
                        minY = Math.min(topLeft.getY(), bottomRight.getY());
                        maxX = Math.max(topLeft.getX(), bottomRight.getX());
                        maxY = Math.max(topLeft.getY(), bottomRight.getY());
                        bounds = new WMSBounds("EPSG:" + mapEpsg, minX, minY, maxX, maxY); //$NON-NLS-1$
                    }

                    URI uri;
                    synchronized (this) {
                        uri = WMSUtil.getMapURI(capabilities, configuration, width, height, bounds, null,
                                format, true);
                    }

                    Proxy proxy = ProxyUtil.findProxy(uri);

                    InputStream in = uri.toURL().openConnection(proxy).getInputStream();

                    BufferedImage image = GraphicsUtilities.loadCompatibleImage(in);

                    // apply transparency to the image
                    BufferedImage result = GraphicsUtilities.createCompatibleTranslucentImage(image.getWidth(),
                            image.getHeight());
                    Graphics2D g = result.createGraphics();
                    try {
                        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f);
                        g.setComposite(ac);
                        g.drawImage(image, 0, 0, null);
                    } finally {
                        g.dispose();
                    }

                    return result;
                }
            } catch (Throwable e) {
                log.warn("Error painting WMS overlay", e); //$NON-NLS-1$
            }
        }
    }

    return null;
}

From source file:Diva.java

@Override
public void paint(Graphics g, JComponent c) {
    Graphics2D g2 = (Graphics2D) g.create();

    // Paint the view.
    super.paint(g2, c);

    if (mActive) {
        // Create a radial gradient, transparent in the middle.
        java.awt.geom.Point2D center = new java.awt.geom.Point2D.Float(mX, mY);
        float radius = 72;
        float[] dist = { 0.0f, 1.0f };
        Color[] colors = { new Color(0.0f, 0.0f, 0.0f, 0.0f), Color.BLACK };
        RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors);
        g2.setPaint(p);//from   w w w .  ja  v  a2s.  c  o  m
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .6f));
        g2.fillRect(0, 0, c.getWidth(), c.getHeight());
    }

    g2.dispose();
}

From source file:net.sourceforge.processdash.ui.web.CGIChartBase.java

/** Generate CGI chart output. */
@Override//from w w w  .ja  v  a  2s .  c om
protected void writeContents() throws IOException {
    buildData(); // get the data for display

    chromeless = (parameters.get("chromeless") != null);
    JFreeChart chart = createChart();

    int width = getIntSetting("width");
    int height = getIntSetting("height");
    Color initGradColor = getColorSetting("initGradColor");
    Color finalGradColor = getColorSetting("finalGradColor");
    chart.setBackgroundPaint(new GradientPaint(0, 0, initGradColor, width, height, finalGradColor));
    if (parameters.get("hideOutline") != null)
        chart.getPlot().setOutlinePaint(INVISIBLE);

    String title = getSetting("title");
    if (chromeless || title == null || title.length() == 0)
        chart.setTitle((TextTitle) null);
    else {
        chart.setTitle(Translator.translate(title));
        String titleFontSize = getSetting("titleFontSize");
        if (titleFontSize != null)
            try {
                float fontSize = Float.parseFloat(titleFontSize);
                TextTitle t = chart.getTitle();
                t.setFont(t.getFont().deriveFont(fontSize));
            } catch (Exception tfe) {
            }
    }

    if (chromeless || parameters.get("hideLegend") != null)
        chart.removeLegend();
    else {
        LegendTitle l = chart.getLegend();
        String legendFontSize = getSetting("legendFontSize");
        if (l != null && legendFontSize != null)
            try {
                float fontSize = Float.parseFloat(legendFontSize);
                l.setItemFont(l.getItemFont().deriveFont(fontSize));
            } catch (Exception lfe) {
            }
    }

    chart.getPlot().setNoDataMessage(resources.getString("No_Data_Message"));

    Axis xAxis = getHorizontalAxis(chart);
    if (xAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideXTickLabels") != null) {
            xAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("xTickLabelFontSize") != null) {
            String tfs = getParameter("xTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            xAxis.setTickLabelFont(xAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    Axis yAxis = getVerticalAxis(chart);
    if (yAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideYTickLabels") != null) {
            yAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("yTickLabelFontSize") != null) {
            String tfs = getParameter("yTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            yAxis.setTickLabelFont(yAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    String axisFontSize = getSetting("axisLabelFontSize");
    if (axisFontSize != null)
        try {
            float fontSize = Float.parseFloat(axisFontSize);
            if (xAxis != null)
                xAxis.setLabelFont(xAxis.getLabelFont().deriveFont(fontSize));
            if (yAxis != null)
                yAxis.setLabelFont(yAxis.getLabelFont().deriveFont(fontSize));
        } catch (Exception afs) {
        }

    ChartRenderingInfo info = (isHtmlMode() ? new ChartRenderingInfo() : null);
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = img.createGraphics();
    if ("auto".equals(getSetting("titleFontSize")))
        maybeAdjustTitleFontSize(chart, g2, width);
    chart.draw(g2, new Rectangle2D.Double(0, 0, width, height), info);
    g2.dispose();

    String outputFormat = getSetting("outputFormat");
    OutputStream imgOut;
    if (isHtmlMode()) {
        imgOut = PngCache.getOutputStream();
    } else {
        imgOut = outStream;
    }
    ImageIO.write(img, outputFormat, imgOut);
    imgOut.flush();
    imgOut.close();
    if (isHtmlMode())
        writeImageHtml(width, height, imgOut.hashCode(), info);
}

From source file:HighlightedButton.java

/**
 * Creates a new instance of HighlightedButton
 *//*from w w  w  .  j  a va  2 s  .c o m*/
public HighlightedButton(String label) {
    super(label);

    // Get the Graphics for the image
    Graphics2D g2d = highlight.createGraphics();

    // Erase the image with a transparent background
    g2d.setComposite(AlphaComposite.Clear);
    g2d.fillRect(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
    g2d.setComposite(AlphaComposite.SrcOver);

    // Draw the highlight
    Point2D center = new Point2D.Float((float) HIGHLIGHT_SIZE / 2.0f, (float) HIGHLIGHT_SIZE / 2.0f);
    float radius = (float) HIGHLIGHT_SIZE / 2.0f;
    float[] dist = { 0.0f, .85f };
    Color[] colors = { Color.white, new Color(255, 255, 255, 0) };
    RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
    g2d.setPaint(paint);
    g2d.fillOval(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
    g2d.dispose();
}

From source file:algo.PlotBar.java

private BufferedImage bufferResize(BufferedImage original, double widthFactor, double heightFactor) {

    // original image width & height
    int w, h;//from   w w w. j  a  v  a  2  s  . c om
    w = original.getHeight();
    h = original.getWidth();
    //        System.out.println(original.getHeight());
    //        System.out.println(original.getWidth());

    // new width & height calculated by multiplying factor
    int newWidth = new Double(original.getWidth() * widthFactor).intValue();
    int newHeight = new Double(original.getWidth() * heightFactor).intValue();

    // new resized image
    BufferedImage buffResized = new BufferedImage(newWidth, newHeight, original.getType());

    Graphics2D g = buffResized.createGraphics();

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
    g.dispose();

    return buffResized;
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an {@link Image} for the given rule.
 * /*  w ww  . j a va2  s .c  o m*/
 * @param rule the rule for which to create the image.
 * @param width the image width.
 * @param height the image height.
 * @return the generated image.
 */
public static BufferedImage pointRuleToImage(final Rule rule, int width, int height) {
    DuplicatingStyleVisitor copyStyle = new DuplicatingStyleVisitor();
    rule.accept(copyStyle);
    Rule newRule = (Rule) copyStyle.getCopy();

    int pointSize = 0;
    Stroke stroke = null;
    Symbolizer[] symbolizers = newRule.getSymbolizers();
    if (symbolizers.length > 0) {
        Symbolizer symbolizer = newRule.getSymbolizers()[0];
        if (symbolizer instanceof PointSymbolizer) {
            PointSymbolizer pointSymbolizer = (PointSymbolizer) symbolizer;
            pointSize = SLDs.pointSize(pointSymbolizer);
            stroke = SLDs.stroke(pointSymbolizer);
        }
    }
    int strokeSize = 0;
    if (stroke != null) {
        strokeSize = SLDs.width(stroke);
        if (strokeSize < 0) {
            strokeSize = 1;
            stroke.setWidth(ff.literal(strokeSize));
        }
    }
    pointSize = pointSize + 2 * strokeSize;
    if (pointSize <= 0) {
        pointSize = width;
    }

    // pointSize = width;
    BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    BufferedImage pointImage = new BufferedImage(pointSize, pointSize, BufferedImage.TYPE_INT_ARGB);
    Point point = d.point(pointSize / 2, pointSize / 2);
    d.drawDirect(pointImage, d.feature(point), newRule);
    Graphics2D g2d = finalImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    if (pointSize > width || pointSize > height) {
        g2d.drawImage(pointImage, 0, 0, width, height, 0, 0, pointSize, pointSize, null);
    } else {
        int x = width / 2 - pointSize / 2;
        int y = height / 2 - pointSize / 2;
        g2d.drawImage(pointImage, x, y, null);
    }
    g2d.dispose();

    return finalImage;
}

From source file:dcstore.web.ImagesWeb.java

private void resizeImage(String inPath, int w, int h, String outPath) {
    try {//from  w  w  w .j ava  2 s.  c om
        BufferedImage originalImage = ImageIO.read(new File(inPath));
        int ow, oh;
        ow = originalImage.getWidth();
        oh = originalImage.getHeight();
        double ratio = (double) ow / (double) oh;
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        int ch = (int) Math.round(w / ratio);

        BufferedImage resizedImage = new BufferedImage(w, h, type);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.white);
        g.fillRect(0, 0, w, h);
        g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null);
        g.dispose();
        ImageIO.write(resizedImage, "jpg", new File(outPath));
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage("",
                new FacesMessage("Error while resizeing image: " + e.getMessage()));
    }
}