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:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from  w ww. j  a va  2s .  co m
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from   w w  w  . j a  v  a  2s .  com
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Export jfreechart to image format. File must have an extension like jpg,
 * png, pdf, svg, eps. Otherwise export will fail.
 *
 * @param file Destination Filedescriptor
 * @param chart JFreechart/*from   w w  w  . j  a  v  a 2s  .c o m*/
 * @throws Exception
 */
public boolean export(File file, JFreeChart chart) throws Exception {

    /*Get extension from file - File must have one extension of
     jpg,png,pdf,svg,eps. Otherwise the export will fail.
     */
    String ext = JFUtils.getExtension(file);

    //  TODO - Make x,y variable
    int x, y;
    // Set size for image (jpg)
    x = 550;
    y = 470;

    int found = 0;

    // JPEG
    if (ext.equalsIgnoreCase("jpg")) {
        ChartUtilities.saveChartAsJPEG(file, chart, x, y);
        found++;
    }
    // PNG
    if (ext.equalsIgnoreCase("png")) {
        ChartUtilities.saveChartAsPNG(file, chart, x, y);
        found++;
    }

    // PDF
    if (ext.equalsIgnoreCase("pdf")) {

        //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart);
        // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !)
        Rectangle pagesize = new Rectangle(x, y);

        Document document = new Document(pagesize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(x, y);

        Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());

        // Draw doesn't works with Rectangle argument - use rectangle2D instead !
        //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y));
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y);
        chart.draw(g2, r2d2);

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();

        found++;

    }

    // SVG
    if (ext.equalsIgnoreCase("svg")) {
        // When exporting to SVG don't forget this VERY important line:
        // svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz
        // Get a DOMImplementation
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        //chart.draw(svgGenerator,new Rectangle(x,y));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y));

        boolean useCSS = true; // we want to use CSS style attribute

        Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
        found++;
    }

    if (ext.equalsIgnoreCase("eps")) {

        //Graphics2D g = new EpsGraphics2D();
        FileOutputStream out = new FileOutputStream(file);
        //Writer out=new FileWriter(file);
        Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB);

        chart.draw(g, new Rectangle2D.Double(0, 0, x, y));
        //Writer out=new FileWriter(file);
        out.write(g.toString().getBytes());
        out.close();
        found++;
    }

    if (found == 0) {
        throw new IllegalArgumentException("File format '" + ext + "' not supported!");
    }

    return true;

}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

@Override
public BufferedImage createCaptcha(char[] text) {
    if (text == null || text.length == 0) {
        throw new IllegalArgumentException("No captcha text given");
    }// ww  w.j a  v  a  2s  .c om

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setBackground(Color.WHITE);
    g2d.setColor(Color.BLACK);

    clearCanvas(g2d);

    if (showGrid) {
        drawGrid(g2d);
    }

    int charMaxWidth = width / text.length;
    int xPos = 0;
    for (char ch : text) {
        drawCharacter(g2d, ch, xPos, charMaxWidth);
        xPos += charMaxWidth;
    }

    g2d.dispose();
    return image;
}

From source file:PSDReader.java

/**
 * Gets the image contents of frame n. Note that this expands the image to the
 * full frame size (if the layer was smaller) and any subsequent use of
 * getLayer() will return the full image.
 * /*www .j a  va  2 s .  c  o  m*/
 * @return BufferedImage representation of frame, or null if n is invalid.
 */
public BufferedImage getFrame(int n) {
    BufferedImage im = null;
    if ((n >= 0) && (n < nLayers)) {
        im = frames[n];
        LayerInfo info = layers[n];
        if ((info.w != width) || (info.h != height)) {
            BufferedImage temp = new BufferedImage(width, height, ImageType);
            Graphics2D gc = temp.createGraphics();
            gc.drawImage(im, info.x, info.y, null);
            gc.dispose();
            im = temp;
            frames[n] = im;
        }
    }
    return im;
}

From source file:SimpleAttributes.java

public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setBackground(Color.GRAY);
    g2d.clearRect(0, 0, getWidth(), getHeight());

    // String and line with default attributes
    g2d.drawString("Default Font", 10, 20);
    g2d.drawLine(10, 22, 80, 22);/*from  ww w  .  j  av  a 2s. co  m*/

    // Change the font, foreground color, and Stroke
    g2d.setFont(g.getFont().deriveFont(Font.BOLD | Font.ITALIC, 24f));
    g2d.setColor(Color.WHITE);
    g2d.setStroke(new BasicStroke(10f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));

    // String and line with new attributes
    g2d.drawString("New Font", 10, 50);
    g2d.drawLine(10, 57, 120, 57);
    g2d.dispose();
}

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

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * //from   w ww .j a v a 2  s  . c  o  m
 * @param rulesWrapperList the list of rules wrapper.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage lineRulesWrapperToImage(final List<RuleWrapper> rulesWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper rule : rulesWrapperList) {
        BufferedImage tmpImage = Utilities.lineRuleWrapperToImage(rule, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

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

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * //from w  ww  .j av  a 2  s. co  m
 * @param rulesWrapperList the list of rules wrapper.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage polygonRulesWrapperToImage(final List<RuleWrapper> rulesWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper rule : rulesWrapperList) {
        BufferedImage tmpImage = Utilities.polygonRuleWrapperToImage(rule, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//from w  ww  .java 2  s  . c o m
 * @param destFile
 * @param quality
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeJpeg(Image img, String destFile, float quality, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.

    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:de.tuttas.restful.SchuelerManager.java

private BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight,
        boolean preserveAlpha) {
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }/*from w  ww .jav a2 s  . com*/
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    return scaledBI;
}