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:eu.udig.style.advanced.points.PointStyleManager.java

private TableViewer createStylesTableViewer(Composite parent) {
    final StyleFilter filter = new StyleFilter();
    final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
    searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
    searchText.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ke) {
            filter.setSearchText(searchText.getText());
            stylesViewer.refresh();//from w w w  .j ava2s .  c  om
        }

    });

    stylesViewer = new TableViewer(parent, SWT.SINGLE | SWT.BORDER);
    Table table = stylesViewer.getTable();
    GridData tableGD = new GridData(SWT.FILL, SWT.FILL, true, true);
    tableGD.heightHint = 200;
    table.setLayoutData(tableGD);

    stylesViewer.addFilter(filter);
    stylesViewer.setContentProvider(new IStructuredContentProvider() {
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List<?>) {
                List<?> styles = (List<?>) inputElement;
                StyleWrapper[] array = (StyleWrapper[]) styles.toArray(new StyleWrapper[styles.size()]);
                return array;
            }
            return null;
        }

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }
    });

    stylesViewer.setLabelProvider(new LabelProvider() {
        public Image getImage(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                List<FeatureTypeStyleWrapper> featureTypeStyles = styleWrapper
                        .getFeatureTypeStylesWrapperList();
                int iconSize = 48;
                BufferedImage image = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = image.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                for (FeatureTypeStyleWrapper featureTypeStyle : featureTypeStyles) {
                    List<RuleWrapper> rulesWrapperList = featureTypeStyle.getRulesWrapperList();
                    BufferedImage tmpImage = Utilities.pointRulesWrapperToImage(rulesWrapperList, iconSize,
                            iconSize);
                    g2d.drawImage(tmpImage, 0, 0, null);
                }
                g2d.dispose();
                Image convertToSWTImage = AWTSWTImageUtils.convertToSWTImage(image);
                return convertToSWTImage;
            }
            return null;
        }

        public String getText(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                String styleName = styleWrapper.getName();
                if (styleName == null || styleName.length() == 0) {
                    styleName = Utilities.DEFAULT_STYLENAME;
                    styleName = Utilities.checkSameNameStyle(getStyles(), styleName);
                    styleWrapper.setName(styleName);
                }
                return styleName;
            }
            return ""; //$NON-NLS-1$
        }
    });

    stylesViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            ISelection selection = event.getSelection();
            if (!(selection instanceof IStructuredSelection)) {
                return;
            }
            IStructuredSelection sel = (IStructuredSelection) selection;
            if (sel.isEmpty()) {
                return;
            }

            Object selectedItem = sel.getFirstElement();
            if (selectedItem == null) {
                // unselected, show empty panel
                return;
            }

            if (selectedItem instanceof StyleWrapper) {
                currentSelectedStyleWrapper = (StyleWrapper) selectedItem;
            }
        }

    });
    return stylesViewer;
}

From source file:jhplot.HPlotChart.java

/**
 * Export graph into an image file. The the image format is given by
 * extension. "png", "jpg", "eps", "pdf", "svg". In case of "eps", "pdf" and
 * "svg", vector graphics is used.//ww  w .  j  ava2 s. c  o  m
 * 
 * @param filename
 *            file name
 * @param width
 *            width
 * @param height
 *            hight
 */
public void export(String filename, int width, int height) {

    String fname = filename;
    String filetype = "pdf";
    int i = filename.lastIndexOf('.');
    if (i > 0) {
        filetype = fname.substring(i + 1);
    }

    try {
        if (filetype.equalsIgnoreCase("png")) {
            BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = b.createGraphics();

            drawToGraphics2D(g, width, height);
            g.dispose();
            ImageIO.write(b, "png", new File(fname));
        } else if (filetype.equalsIgnoreCase("jpg") || filetype.equalsIgnoreCase("jpeg")) {
            BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = b.createGraphics();
            drawToGraphics2D(g, width, height);
            g.dispose();
            ImageIO.write(b, "jpg", new File(fname));

            /*
             * } else if (filetype.equalsIgnoreCase("eps")) { try {
             * ImageType currentImageType = ImageType.EPS; Rectangle r = new
             * Rectangle (0, 0, width, height);
             * Export.exportComponent(getCanvasPanel(), r, new
             * File(filename), currentImageType); } catch (IOException e) {
             * e.printStackTrace(); } catch
             * (org.apache.batik.transcoder.TranscoderException e) {
             * e.printStackTrace(); }
             */

        } else if (filetype.equalsIgnoreCase("ps")) {
            try {
                ImageType currentImageType = ImageType.PS;
                Rectangle r = new Rectangle(0, 0, width, height);
                Export.exportComponent(cp, r, new File(filename), currentImageType);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (org.apache.batik.transcoder.TranscoderException e) {
                e.printStackTrace();
            }

        } else if (filetype.equalsIgnoreCase("eps")) {

            try {
                FileOutputStream outputStream = new FileOutputStream(fname);
                org.jibble.epsgraphics.EpsGraphics2D g = new org.jibble.epsgraphics.EpsGraphics2D(
                        "HChart canvas", outputStream, 0, 0, width, height);// #Create
                // a
                // new
                // document
                // with
                // bounding
                // box
                // 0 <=
                // x <=
                // 100
                // and
                // 0 <=
                // y <=
                // 100.
                drawToGraphics2D(g, width, height);
                g.flush();
                g.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Problem writing eps");
            }

        } else if (filetype.equalsIgnoreCase("pdf")) {

            try {
                FileOutputStream outputStream = new FileOutputStream(fname);
                com.lowagie.text.pdf.FontMapper mapper = new com.lowagie.text.pdf.DefaultFontMapper();
                com.lowagie.text.Rectangle pagesize = new com.lowagie.text.Rectangle(width, height);
                com.lowagie.text.Document document = new com.lowagie.text.Document(pagesize, 50, 50, 50, 50);
                try {
                    com.lowagie.text.pdf.PdfWriter writer = com.lowagie.text.pdf.PdfWriter.getInstance(document,
                            outputStream);
                    // document.addAuthor("JFreeChart");
                    // document.addSubject("Jylab");
                    document.open();
                    com.lowagie.text.pdf.PdfContentByte cb = writer.getDirectContent();
                    com.lowagie.text.pdf.PdfTemplate tp = cb.createTemplate(width, height);
                    Graphics2D g = tp.createGraphics(width, height, mapper);
                    // Rectangle2D r2D = new Rectangle2D.Double(0, 0, width,
                    // height);

                    drawToGraphics2D(g, width, height);
                    g.dispose();
                    cb.addTemplate(tp, 0, 0);

                } catch (com.lowagie.text.DocumentException de) {
                    System.err.println(de.getMessage());
                }
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Cannot find itext library, cannot create pdf.");
            }

        } else if (filetype.equalsIgnoreCase("svg")) {

            try {

                // import org.apache.batik.dom.GenericDOMImplementation;
                // import org.apache.batik.svggen.SVGGraphics2D;

                org.w3c.dom.DOMImplementation domImpl = org.apache.batik.dom.GenericDOMImplementation
                        .getDOMImplementation();
                // Create an instance of org.w3c.dom.Document
                org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
                // Create an instance of the SVG Generator
                org.apache.batik.svggen.SVGGraphics2D svgGenerator = new org.apache.batik.svggen.SVGGraphics2D(
                        document);
                svgGenerator.setSVGCanvasSize(new Dimension(width, height));
                // set the precision to avoid a null pointer exception in
                // Batik 1.5
                svgGenerator.getGeneratorContext().setPrecision(6);
                // Ask the chart to render into the SVG Graphics2D
                // implementation

                drawToGraphics2D(svgGenerator, width, height);
                // chart.draw(svgGenerator, new Rectangle2D.Double(0, 0,
                // width, height), null);
                // Finally, stream out SVG to a file using UTF-8 character
                // to
                // byte encoding
                boolean useCSS = true;
                Writer out = new OutputStreamWriter(new FileOutputStream(new File(filename)), "UTF-8");
                svgGenerator.stream(out, useCSS);
                out.close();

            } catch (org.w3c.dom.DOMException e) {
                System.err.println("Problem writing to SVG");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Missing Batik libraries?");
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET,
        RequestMethod.POST })//from ww w  .j a v  a 2 s.  c om
public void doExport(@RequestParam("bbox") final String bbox,
        @RequestParam(value = "size", required = false) final String size,
        @RequestParam(value = "layerDefs", required = false) final String layerDefs,
        @RequestParam(value = "transparent", required = false) final String transparent,
        final HttpServletResponse response) throws IOException {
    double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0;
    if (bbox != null && bbox.length() > 0) {
        final String[] tokens = m_patternComma.split(bbox);
        if (tokens.length == 4) {
            xmin = Double.parseDouble(tokens[0]);
            ymin = Double.parseDouble(tokens[1]);
            xmax = Double.parseDouble(tokens[2]);
            ymax = Double.parseDouble(tokens[3]);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "bbox is not in the form xmin,ymin,xmax,ymax");
            return;
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty");
        return;
    }

    final double xdel = xmax - xmin;
    final double ydel = ymax - ymin;

    int imageWidth = 400;
    int imageHeight = 400;
    if (size != null && size.length() > 0) {
        final String[] tokens = m_patternComma.split(size);
        if (tokens.length == 2) {
            imageWidth = Integer.parseInt(tokens[0], 10);
            imageHeight = Integer.parseInt(tokens[1], 10);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height");
            return;
        }
    }
    String where = null;
    double lo = Double.NaN;
    double hi = Double.NaN;
    int[] ramp = null;
    if (layerDefs != null) {
        final String[] tokens = m_patternSemiColon.split(layerDefs);
        for (final String token : tokens) {
            final String[] keyval = m_patternEqual.split(token.substring(2));
            if (keyval.length == 2) {
                final String key = keyval[0];
                final String val = keyval[1];
                if ("lo".equalsIgnoreCase(key)) {
                    lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("hi".equalsIgnoreCase(key)) {
                    hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("ramp".equalsIgnoreCase(key)) {
                    ramp = parseRamp(val);
                } else if ("where".equalsIgnoreCase(key)) {
                    where = val;
                }
            }
        }
    }
    if (ramp == null) {
        ramp = new int[] { 0xFFFFFF, 0x000000 };
    }

    final Range range = new Range();
    final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range);
    if (!Double.isNaN(lo)) {
        range.lo = lo;
    }
    if (!Double.isNaN(hi)) {
        range.hi = hi;
    }
    range.dd = range.hi - range.lo;

    final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB
            : BufferedImage.TYPE_INT_RGB;
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb);
    final Graphics2D graphics = bufferedImage.createGraphics();
    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        graphics.setBackground(new Color(0, 0, 0, 0));

        drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet());
    } finally {
        graphics.dispose();
    }

    // bufferedImage = m_op.filter(bufferedImage, null);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024);
    ImageIO.write(bufferedImage, "PNG", baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("image/png");
    response.setContentLength(baos.size());
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();
}

From source file:com.github.dactiv.fear.service.service.account.AccountService.java

/**
 * ??//from  ww w  .  j a v  a2  s . com
 *
 * @param sourcePath   ?
 * @param targetPath   ??
 * @param portraitSize ?
 *
 * @throws IOException
 */
private String scaleImage(String sourcePath, String targetPath, PortraitSize portraitSize) throws IOException {
    InputStream inputStream = new FileInputStream(sourcePath);

    BufferedImage source = ImageIO.read(inputStream);
    ColorModel targetColorModel = source.getColorModel();

    inputStream.close();

    int width = portraitSize.getWidth();
    int height = portraitSize.getHeight();

    BufferedImage target = new BufferedImage(targetColorModel,
            targetColorModel.createCompatibleWritableRaster(width, height),
            targetColorModel.isAlphaPremultiplied(), null);

    Image scaleImage = source.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    Graphics2D g = target.createGraphics();
    g.drawImage(scaleImage, 0, 0, width, height, null);
    g.dispose();

    String result = targetPath + portraitSize.getName();
    FileOutputStream fileOutputStream = new FileOutputStream(result);
    ImageIO.write(target, PORTRAIT_PIC_TYPE, fileOutputStream);

    fileOutputStream.close();

    return result;
}

From source file:painting.IconDisplayer.java

protected void paintComponent(Graphics g) {
    if (isOpaque()) { //paint background
        g.setColor(getBackground());//from   www .ja v a  2 s .  c o  m
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    if (icon != null) {
        //Draw the icon over and over, right aligned.
        Insets insets = getInsets();
        int iconWidth = icon.getIconWidth();
        int iconX = getWidth() - insets.right - iconWidth;
        int iconY = insets.top;
        boolean faded = false;

        //Copy the Graphics object, which is actually
        //a Graphics2D object.  Cast it so we can
        //set alpha composite.
        Graphics2D g2d = (Graphics2D) g.create();

        //Draw the icons, starting from the right.
        //After the first one, the rest are faded.
        //We won't bother painting icons that are clipped.
        g.getClipBounds(clipRect);
        while (iconX >= insets.left) {
            iconRect.setBounds(iconX, iconY, iconWidth, icon.getIconHeight());
            if (iconRect.intersects(clipRect)) {
                icon.paintIcon(this, g2d, iconX, iconY);
            }
            iconX -= (iconWidth + pad);
            if (!faded) {
                g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
                faded = true;
            }
        }

        g2d.dispose(); //clean up
    }
}

From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java

/**
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * @param src - source image to scale//w  ww  .j a  v a 2s. c  o m
 * @param w - desired width
 * @param h - desired height
 * @return - the new resized image
 */
private BufferedImage getScaledImage(BufferedImage src, int orientation, int w, int h) throws Exception {
    int finalW = w;
    int finalH = h;

    if (h == -1)
        finalH = w;
    if (w == -1)
        finalW = h;

    double factor = 1.0d;
    if (src.getWidth() > src.getHeight()) {
        factor = ((double) src.getHeight() / (double) src.getWidth());
        finalH = (int) (finalW * factor);
    } else {
        factor = ((double) src.getWidth() / (double) src.getHeight());
        finalW = (int) (finalH * factor);
    }

    BufferedImage scaledImage = new BufferedImage(finalW, finalH, src.getType());
    Graphics2D g = scaledImage.createGraphics();

    try {
        //AffineTransform at = AffineTransform.getScaleInstance((double) finalw / src.getWidth(), (double) finalh/ src.getHeight());
        AffineTransform at = getExifTransformation(orientation, (double) finalW, (double) finalH,
                (double) finalW / src.getWidth(), (double) finalH / src.getHeight());
        return transformImage(src, at);
        //g.drawRenderedImage(src, at);
        //return scaledImage;
    } finally {
        g.dispose();
    }

    /**
    BufferedImage resizedImg = new BufferedImage(finalw, finalh, src.getType());
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(src, 0, 0, finalw, finalh, null);
    g2.dispose();
    return resizedImg;
    **/
}

From source file:keel.GraphInterKeel.datacf.visualizeData.VisualizePanelCharts2D.java

private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);//from  w w  w.j a va 2s.c om
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this,
                "File " + nombre + " already exists. Do you want to replace it?", "Confirm",
                JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412, new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}

From source file:org.kuali.mobility.people.service.PeopleServiceImpl.java

@Override
public BufferedImage generateObfuscatedImage(String text) {
    int width = 250;
    int height = 25;

    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = bufferedImage.createGraphics();
    Font font = new Font("Arial", Font.PLAIN, 14);
    g2d.setFont(font);/*w  w w .j  a va 2s.  c o  m*/

    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    g2d.setRenderingHints(rh);

    Paint bg = new Color(255, 255, 255);
    g2d.setPaint(bg);
    g2d.fillRect(0, 0, width, height);

    int x = 0;
    int y = height - 7;

    Paint textPaint = new Color(0, 0, 0);
    g2d.setPaint(textPaint);
    g2d.drawString(text, x, y);

    g2d.dispose();
    return bufferedImage;
}

From source file:IconDisplayer.java

protected void paintComponent(Graphics g) {
    if (isOpaque()) { //paint background
        g.setColor(getBackground());/*  w ww.  j ava2  s  .co m*/
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    if (icon != null) {
        //Draw the icon over and over, right aligned.
        Insets insets = getInsets();
        int iconWidth = icon.getIconWidth();
        int iconX = getWidth() - insets.right - iconWidth;
        int iconY = insets.top;
        boolean faded = false;

        //Copy the Graphics object, which is actually
        //a Graphics2D object. Cast it so we can
        //set alpha composite.
        Graphics2D g2d = (Graphics2D) g.create();

        //Draw the icons, starting from the right.
        //After the first one, the rest are faded.
        //We won't bother painting icons that are clipped.
        g.getClipBounds(clipRect);
        while (iconX >= insets.left) {
            iconRect.setBounds(iconX, iconY, iconWidth, icon.getIconHeight());
            if (iconRect.intersects(clipRect)) {
                icon.paintIcon(this, g2d, iconX, iconY);
            }
            iconX -= (iconWidth + pad);
            if (!faded) {
                g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
                faded = true;
            }
        }

        g2d.dispose(); //clean up
    }
}

From source file:edworld.pdfreader4humans.PDFReader.java

public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor,
        boolean showStructure) throws IOException {
    Map<String, Font> fonts = new HashMap<String, Font>();
    PDRectangle cropBox = getPageCropBox(pageNumber);
    BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling),
            Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setBackground(backgroundColor);
    graphics.clearRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(backgroundColor);/*from   w w  w. j  ava 2 s .  c  o  m*/
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(inkColor);
    graphics.scale(scaling, scaling);
    for (Component component : getFirstLevelComponents(pageNumber))
        draw(component, graphics, inkColor, backgroundColor, showStructure, fonts);
    graphics.dispose();
    return image;
}