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.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

public static BufferedImage renderMindMapAsImage(final MindMap model, final MindMapPanelConfig cfg,
        final boolean expandAll) {
    final MindMap workMap = new MindMap(model, null);
    workMap.resetPayload();/*from   ww w  .  j  a v  a  2s  .co m*/

    if (expandAll) {
        MindMapUtils.removeCollapseAttr(workMap);
    }

    final Dimension2D blockSize = calculateSizeOfMapInPixels(workMap, cfg, expandAll);
    if (blockSize == null) {
        return null;
    }

    final BufferedImage img = new BufferedImage((int) blockSize.getWidth(), (int) blockSize.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    final Graphics2D gfx = img.createGraphics();
    try {
        Utils.prepareGraphicsForQuality(gfx);
        gfx.setClip(0, 0, img.getWidth(), img.getHeight());
        layoutFullDiagramWithCenteringToPaper(gfx, workMap, cfg, blockSize);
        drawOnGraphicsForConfiguration(gfx, cfg, workMap, false, null);
    } finally {
        gfx.dispose();
    }
    return img;
}

From source file:de.thm.arsnova.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString//from  ww w .  j  av  a 2s . c  o  m
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
public String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append("data:image/");
            result.append(extension);
            result.append(";base64,");

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            ImageIO.write(newImage, extension, output);

            output.flush();
            output.close();

            result.append(Base64.encodeBase64String(output.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage());
            return null;
        }
    }
}

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

private void updateLegend() {
    try {//from w  ww  .j  av  a2s .  c o  m
        ArrayList<Image> legends = new ArrayList<Image>(4);
        if (singleRenderer != null && singleRenderer.getLegend() != null) {
            legends.add(singleRenderer.getLegend());
        }
        if (rowGroupRenderer != null && rowGroupRenderer.getLegend() != null) {
            legends.add(rowGroupRenderer.getLegend());
        }
        if (columnGroupRenderer != null && columnGroupRenderer.getLegend() != null) {
            legends.add(columnGroupRenderer.getLegend());
        }
        if (rowColumnGroupRenderer != null && rowColumnGroupRenderer.getLegend() != null) {
            legends.add(rowColumnGroupRenderer.getLegend());
        }

        if (!legends.isEmpty()) {
            int margin = 5;
            int imageWidth = 0;
            int imageHeight = 0;
            for (Image l : legends) {
                imageHeight += margin * 2 + l.getHeight(null);
                if (imageWidth < l.getWidth(null)) {
                    imageWidth = l.getWidth(null);
                }
            }

            imageWidth += margin * 2;

            if (imageWidth > 0 && imageHeight > 0) {
                legend = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                        .getDefaultConfiguration()
                        .createCompatibleImage(imageWidth, imageHeight, Transparency.TRANSLUCENT);
                Graphics2D g2D = legend.createGraphics();
                g2D.translate(margin, 0);
                for (Image l : legends) {
                    g2D.translate(0, margin);
                    g2D.drawImage(l, 0, 0, null);
                    g2D.translate(0, margin + l.getHeight(null));
                }
                g2D.dispose();
            }

        }
    } catch (Exception e) {

    }
}

From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.MatrixChart.java

private void buildFinalChart(String title, String subTitle, String filename, String xAxisLabel,
        String yAxisLabel, int width, int height) {
    this.buildMainChart(title, subTitle, xAxisLabel, yAxisLabel, filename);

    this.buildLegendChart(5);

    BufferedImage mainChartImage = this.mainChart.createBufferedImage(width, height);
    BufferedImage legendChartImage = this.legendChart.createBufferedImage(width / 6, height / 3);
    BufferedImage info = null;/*  ww w . jav  a 2 s.  c  o  m*/
    try {
        info = ImageIO.read(MatrixChart.logoFile);
    } catch (IOException ex) {
    }

    BufferedImage total = new BufferedImage(width + (width / 6), height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = total.createGraphics();

    g.drawImage(mainChartImage, 0, 0, null);
    g.drawImage(legendChartImage, width, height / 4, null);
    g.setPaint(Color.WHITE);
    g.fillRect(width, 0, width, height / 4);
    g.fillRect(width, (height / 4) + (height / 3), width, height);
    if (info != null) {
        // g.drawImage(info, (width+(width/6))-info.getWidth(),10, null); //
        // up-right
        g.drawImage(info, (width + (width / 6)) - info.getWidth(), height - info.getHeight(), null); // down-right
    }
    g.dispose();

    try {
        javax.imageio.ImageIO.write(total, "png", XMLHelper.createFileWithDirs(filename));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Resize an image/*from   w  w  w  .j a  v  a2s .  c o m*/
 * 
 * @param originalImage
 * @param width
 * @param height
 * @param type
 * @return
 */
private BufferedImage resize(BufferedImage originalImage, int width, int height, int type) {
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    try {
        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(originalImage, 0, 0, width, height, null);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }

    return resizedImage;
}

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

public void mouseReleased(MouseEvent e) {
    if (MouseUtils.isPopupTrigger(e)) {
        // clear all
        if (zoom_rectangle != null) {
            Graphics2D g2 = (Graphics2D) getGraphics();
            g2.setXORMode(java.awt.Color.gray);
            g2.draw(zoom_rectangle);/*  w  w w .j a  v  a2 s.c o m*/
            g2.dispose();
        }
        mouse_start_point = null;
        zoom_rectangle = null;

        // open popup
        current_peak = findPeakAt(e.getPoint());
        enforceSelection(current_peak);
        createPopupMenu(current_peak != null).show(theChartPanel, e.getX(), e.getY());
    } else {
        if (zoom_rectangle != null && mouse_start_point != null) {
            if (Math.abs(e.getX() - mouse_start_point.getX()) > 10) {
                //if( e.getX() < mouse_start_point.getX() ) {
                // unzoom all
                //    onZoomNone();
                //}
                //else {        

                // zoom area           
                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 new_lower_bound = screenToDataCoordX(start_x);
                double new_upper_bound = screenToDataCoordX(Math.min(end_x, data_area.getMaxX()));
                thePlot.getDomainAxis().setRange(new Range(new_lower_bound, new_upper_bound));
            } else {
                // clear rectangle
                Graphics2D g2 = (Graphics2D) getGraphics();
                g2.setXORMode(java.awt.Color.gray);
                g2.draw(zoom_rectangle);
                g2.dispose();
            }
        }

        // restore zooming
        if (!was_moving && is_moving)
            onActivateZooming();

        zoom_rectangle = null;
        mouse_start_point = null;
    }
}

From source file:gdt.jgui.entity.webset.JWeblinkEditor.java

private void showIconMenu(MouseEvent e) {
    try {/* www  .ja  va2s .  c  o m*/
        iconMenu = new JPopupMenu();
        JMenuItem loadItem = new JMenuItem("Load");
        iconMenu.add(loadItem);
        loadItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        loadItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String favicon$ = "http://www.google.com/s2/favicons?domain=" + addressField.getText();
                    URL url = new URL(favicon$);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    ImageIcon icon = new ImageIcon(ImageIO.read(input));
                    int type = BufferedImage.TYPE_INT_RGB;
                    BufferedImage out = new BufferedImage(24, 24, type);
                    Color background = JWeblinkEditor.this.getBackground();
                    Graphics2D g2 = out.createGraphics();
                    g2.setBackground(background);
                    g2.clearRect(0, 0, 24, 24);
                    Image image = icon.getImage();
                    g2.drawImage(image, 4, 4, null);
                    g2.dispose();
                    icon = new ImageIcon(out);
                    iconIcon.setIcon(icon);
                    input.close();
                } catch (Exception ee) {
                    Logger.getLogger(getClass().getName()).info(ee.toString());
                }
            }
        });
        JMenuItem setItem = new JMenuItem("Set");
        iconMenu.add(setItem);
        setItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        setItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("WeblinkEditor:set icon");
                JIconSelector is = new JIconSelector();
                String isLocator$ = is.getLocator();
                if (entihome$ != null)
                    isLocator$ = Locator.append(isLocator$, Entigrator.ENTIHOME, entihome$);
                if (entityKey$ != null)
                    isLocator$ = Locator.append(isLocator$, EntityHandler.ENTITY_KEY, entityKey$);

                String responseLocator$ = getLocator();
                responseLocator$ = Locator.append(responseLocator$, JRequester.REQUESTER_ACTION,
                        ACTION_SET_ICON);
                responseLocator$ = Locator.append(responseLocator$, BaseHandler.HANDLER_METHOD, "response");
                isLocator$ = Locator.append(isLocator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                        Locator.compressText(responseLocator$));
                JConsoleHandler.execute(console, isLocator$);
            }
        });
        iconMenu.show(e.getComponent(), e.getX(), e.getY());
    } catch (Exception ee) {
        Logger.getLogger(getClass().getName()).severe(ee.toString());
    }
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

public String writeIntoCheck(String filePath, String username, String theAmount, String amountInWords,
        String dateWrote, String person_payingto, String billType) throws IOException, NullPointerException {

    File blueCheck = new File("blank-blue-check.jpg");
    String pathToOriginal = getServletContext().getRealPath("/" + blueCheck);

    File file = new File(pathToOriginal);
    BufferedImage imageToCopy = null;
    try {// w  ww  .java 2s  .  c  o  m
        imageToCopy = ImageIO.read(file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String amount = theAmount;
    String person_gettingPayed = person_payingto;
    String amountinWords = amountInWords;
    String date = dateWrote;
    String bill_type = billType;

    int w = imageToCopy.getWidth();
    int h = imageToCopy.getHeight();
    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setColor(g2d.getBackground());
    g2d.fillRect(0, 0, w, h);
    g2d.drawImage(imageToCopy, 0, -100, null);
    g2d.setPaint(Color.black);
    g2d.setFont(new java.awt.Font("Serif", Font.BOLD, 36));
    //g2d.setFont(new Font("Serif", Font.BOLD, 36));

    FontMetrics fm = g2d.getFontMetrics();
    int x = img.getWidth() - fm.stringWidth(amount) - 100;
    int y = fm.getHeight();
    g2d.drawString(amount, x - 70, y + 335);
    g2d.drawString(person_gettingPayed, x - 800, y + 329);
    g2d.drawString(amountinWords, x - 940, y + 390);
    g2d.drawString(date, x - 340, y + 245);
    g2d.drawString(bill_type, x - 900, y + 530);

    String signature = "Use The Force";
    g2d.setFont(new java.awt.Font("Monotype Corsiva", Font.BOLD | Font.ITALIC, 36));
    g2d.drawString(signature, x - 340, y + 530);
    g2d.dispose();
    /*write check to file*/
    String filename = fileNameGenerator(username);
    String fullname = filePath + "_" + filename + ".jpg";
    ImageIO.write(img, "jpg", new File(fullname));
    return fullname;
}

From source file:TapTapTap.java

@Override
public void paint(Graphics g, JComponent c) {
    int w = c.getWidth();
    int h = c.getHeight();

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

    if (!mIsRunning) {
        return;/*from  w  w w  . j a va 2  s .  c om*/
    }

    Graphics2D g2 = (Graphics2D) g.create();

    float fade = (float) mFadeCount / (float) mFadeLimit;
    // Gray it out.
    Composite urComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f * fade));
    g2.fillRect(0, 0, w, h);
    g2.setComposite(urComposite);

    // Paint the wait indicator.
    int s = Math.min(w, h) / 5;
    int cx = w / 2;
    int cy = h / 2;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setStroke(new BasicStroke(s / 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2.setPaint(Color.white);
    g2.rotate(Math.PI * mAngle / 180, cx, cy);
    for (int i = 0; i < 12; i++) {
        float scale = (11.0f - (float) i) / 11.0f;
        g2.drawLine(cx + s, cy, cx + s * 2, cy);
        g2.rotate(-Math.PI / 6, cx, cy);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, scale * fade));
    }

    g2.dispose();
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private BufferedImage rotateImage(BufferedImage masterImage, int angle) {
    int virtualAngle = getVirtualAngle(angle);
    Dimension size = new Dimension(masterImage.getWidth(), masterImage.getHeight());
    int masterWidth = masterImage.getWidth();
    int masterHeight = masterImage.getHeight();

    double x = 0; //masterWidth / 2.0;
    double y = 0; //masterHeight / 2.0;

    switch (virtualAngle) {
    case 0://w  w w.  ja va  2s  .c o m
        break;
    case 180:
        break;
    case 90:
    case 270:
        size = new Dimension(masterImage.getHeight(), masterImage.getWidth());
        x = (masterHeight - masterWidth) / 2.0;
        y = (masterWidth - masterHeight) / 2.0;
        break;
    }
    BufferedImage renderedImage = new BufferedImage(size.width, size.height, masterImage.getTransparency());
    Graphics2D g2d = renderedImage.createGraphics();

    AffineTransform at = AffineTransform.getTranslateInstance(x, y);

    at.rotate(Math.toRadians(virtualAngle), masterWidth / 2.0, masterHeight / 2.0);
    g2d.drawImage(masterImage, at, null);

    g2d.dispose();
    return renderedImage;
}