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:components.SizeDisplayer.java

protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create(); //copy g
    Dimension minSize = getMinimumSize();
    Dimension prefSize = getPreferredSize();
    Dimension size = getSize();/*w ww. j  av a 2  s .com*/
    int prefX = 0, prefY = 0;

    //Set hints so text looks nice.
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    //Draw the maximum size rectangle if we're opaque.
    if (isOpaque()) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, size.width, size.height);
    }

    //Draw the icon.
    if (icon != null) {
        Composite oldComposite = g2d.getComposite();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
        icon.paintIcon(this, g2d, (size.width - icon.getIconWidth()) / 2,
                (size.height - icon.getIconHeight()) / 2);
        g2d.setComposite(oldComposite);
    }

    //Draw the preferred size rectangle.
    prefX = (size.width - prefSize.width) / 2;
    prefY = (size.height - prefSize.height) / 2;
    g2d.setColor(Color.RED);
    g2d.drawRect(prefX, prefY, prefSize.width - 1, prefSize.height - 1);

    //Draw the minimum size rectangle.
    if (minSize.width != prefSize.width || minSize.height != prefSize.height) {
        int minX = (size.width - minSize.width) / 2;
        int minY = (size.height - minSize.height) / 2;
        g2d.setColor(Color.CYAN);
        g2d.drawRect(minX, minY, minSize.width - 1, minSize.height - 1);
    }

    //Draw the text.
    if (text != null) {
        Dimension textSize = getTextSize(g2d);
        g2d.setColor(getForeground());
        g2d.drawString(text, (size.width - textSize.width) / 2,
                (size.height - textSize.height) / 2 + g2d.getFontMetrics().getAscent());
    }
    g2d.dispose();
}

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

/**
 * Draw an overlay on the image, such as a box cover specific for videosource, container, certification if wanted
 *
 * @param movie/*w  w  w. j a  va 2 s .  c o  m*/
 * @param bi
 * @param offsetY
 * @param offsetX
 * @return
 */
private BufferedImage drawOverlay(Movie movie, BufferedImage bi, int offsetX, int offsetY) {

    String source;
    if (overlaySource.equalsIgnoreCase(VIDEOSOURCE)) {
        source = movie.getVideoSource();
    } else if (overlaySource.equalsIgnoreCase(CERTIFICATION)) {
        source = movie.getCertification();
    } else if (overlaySource.equalsIgnoreCase(CONTAINER)) {
        source = movie.getContainer();
    } else {
        source = DEFAULT;
    }

    // Make sure the source is formatted correctly
    source = source.toLowerCase().trim();

    // Check for a blank or an UNKNOWN source and correct it
    if (StringTools.isNotValidString(source)) {
        source = DEFAULT;
    }

    String overlayFilename = source + "_overlay_" + imageType + ".png";

    try {
        BufferedImage biOverlay = GraphicTools.loadJPEGImage(getResourcesPath() + overlayFilename);

        BufferedImage returnBI = new BufferedImage(biOverlay.getWidth(), biOverlay.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2BI = returnBI.createGraphics();
        g2BI.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2BI.drawImage(bi, offsetX, offsetY, offsetX + bi.getWidth(), offsetY + bi.getHeight(), 0, 0,
                bi.getWidth(), bi.getHeight(), null);
        g2BI.drawImage(biOverlay, 0, 0, null);

        g2BI.dispose();

        return returnBI;
    } catch (FileNotFoundException ex) {
        LOG.warn(LOG_FAILED_TO_LOAD, overlayFilename);
    } catch (IOException ex) {
        LOG.warn("Failed drawing overlay to {}. Please check that {} is in the resources directory.",
                movie.getBaseName(), overlayFilename);
    }

    return bi;
}

From source file:lucee.runtime.img.Image.java

/**
  * Convenience method that returns a scaled instance of the
  * provided {@code BufferedImage}./*from  www  .j  av a  2  s  .c  o m*/
  *
  * @param img the original image to be scaled
  * @param targetWidth the desired width of the scaled instance,
  *    in pixels
  * @param targetHeight the desired height of the scaled instance,
  *    in pixels
  * @param hint one of the rendering hints that corresponds to
  *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
  *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
  * @param higherQuality if true, this method will use a multi-step
  *    scaling technique that provides higher quality than the usual
  *    one-step technique (only useful in downscaling cases, where
  *    {@code targetWidth} or {@code targetHeight} is
  *    smaller than the original dimensions, and generally only when
  *    the {@code BILINEAR} hint is specified)
  * @return a scaled version of the original {@code BufferedImage}
  */
private BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    // functionality not supported in java 1.4
    int transparency = Transparency.OPAQUE;
    try {
        transparency = img.getTransparency();
    } catch (Throwable t) {
    }
    int type = (transparency == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

    BufferedImage ret = img;
    int w, h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

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

/**
 * Draw rounded corners on the image//w  ww .j a va 2s.c  o m
 *
 * @param bi
 * @return
 */
protected BufferedImage drawRoundCorners(BufferedImage bi) {
    BufferedImage newImg = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D newGraphics = newImg.createGraphics();
    newGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    RoundRectangle2D.Double rect = new RoundRectangle2D.Double(0, 0, bi.getWidth(), bi.getHeight(),
            rcqFactor * cornerRadius, rcqFactor * cornerRadius);
    newGraphics.setClip(rect);
    newGraphics.drawImage(bi, 0, 0, null);

    newGraphics.dispose();
    return newImg;
}

From source file:au.org.ala.biocache.web.MapController.java

@Deprecated
@RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET)
public void pointsWmsImage(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj,
        @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel,
        @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize,
        @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol,
        @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString,
        @RequestParam(value = "type", required = false, defaultValue = "normal") String type,
        @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour,
        HttpServletResponse response) throws Exception {

    // size of the circles
    int size = symsize.intValue();
    int width = widthObj.intValue();
    int height = heightObj.intValue();

    requestParams.setStart(0);/*  w  w  w  . j  a v  a2 s  . c  om*/
    requestParams.setPageSize(Integer.MAX_VALUE);
    String query = requestParams.getQ();
    String[] filterQuery = requestParams.getFq();

    if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) {
        displayBlankImage(width, height, false, response);
        return;
    }

    // let's force it to PNG's for now 
    response.setContentType("image/png");

    // Convert array to list so we append more values onto it
    ArrayList<String> fqList = null;
    if (filterQuery != null) {
        fqList = new ArrayList<String>(Arrays.asList(filterQuery));
    } else {
        fqList = new ArrayList<String>();
    }

    // the bounding box
    double[] bbox = new double[4];
    int i;
    i = 0;
    for (String s : bboxString.split(",")) {
        try {
            bbox[i] = Double.parseDouble(s);
            i++;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    double pixelWidth = (bbox[2] - bbox[0]) / width;
    double pixelHeight = (bbox[3] - bbox[1]) / height;
    bbox[0] += pixelWidth / 2;
    bbox[2] -= pixelWidth / 2;
    bbox[1] += pixelHeight / 2;
    bbox[3] -= pixelHeight / 2;

    //offset for points bounding box by size
    double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2);
    double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2);

    //adjust offset for pixel height/width
    xoffset += pixelWidth;
    yoffset += pixelHeight;

    double[] bbox2 = new double[4];
    bbox2[0] = convertMetersToLng(bbox[0] - xoffset);
    bbox2[1] = convertMetersToLat(bbox[1] - yoffset);
    bbox2[2] = convertMetersToLng(bbox[2] + xoffset);
    bbox2[3] = convertMetersToLat(bbox[3] + yoffset);

    bbox[0] = convertMetersToLng(bbox[0]);
    bbox[1] = convertMetersToLat(bbox[1]);
    bbox[2] = convertMetersToLng(bbox[2]);
    bbox[3] = convertMetersToLat(bbox[3]);

    double[] pbbox = new double[4]; //pixel bounding box
    pbbox[0] = convertLngToPixel(bbox[0]);
    pbbox[1] = convertLatToPixel(bbox[1]);
    pbbox[2] = convertLngToPixel(bbox[2]);
    pbbox[3] = convertLatToPixel(bbox[3]);

    String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3];
    bboxToQuery(bboxString2, fqList);

    PointType pointType = getPointTypeForZoomLevel(zoomLevel);

    String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array

    requestParams.setFq(newFilterQuery);

    List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType);
    logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size());

    if (points.size() == 0) {
        displayBlankImage(width, height, false, response);
        return;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.RED);

    int x, y;
    int pointWidth = size * 2;
    double width_mult = (width / (pbbox[2] - pbbox[0]));
    double height_mult = (height / (pbbox[1] - pbbox[3]));

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Color oColour = Color.decode(outlineColour);

    for (i = 0; i < points.size(); i++) {
        OccurrencePoint pt = points.get(i);
        float lng = pt.getCoordinates().get(0).floatValue();
        float lat = pt.getCoordinates().get(1).floatValue();

        x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult);
        y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult);

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);
        } else {
            g.setPaint(Color.blue);
        }

        // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        g.draw(shp);
        g.fill(shp);
        if (outlinePoints) {
            g.setPaint(oColour);
            g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        }
    }

    g.dispose();

    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:business.model.CaptchaModel.java

/**
 *
 * @param CaptchaText/*from   w ww . j  a  va2s .  co m*/
 * @return
 */
public static BufferedImage CreateCaptchaImageOld(String CaptchaText) {
    BufferedImage localBufferedImage = new BufferedImage(width, height, 1);
    try {
        Graphics2D localGraphics2D = localBufferedImage.createGraphics();
        //        List<Font> fonts = FontFactory.getListFont();
        List<Font> fonts = new ArrayList<Font>();
        if (fonts.isEmpty()) {
            fonts.add(new Font("Nimbus Roman No9 L", 1, 30));
            fonts.add(new Font("VN-NTime", 1, 30));
            fonts.add(new Font("DT-Times", 1, 30));
            fonts.add(new Font("Times New Roman", 1, 30));
            fonts.add(new Font("Vni-Book123", 1, 30));
            fonts.add(new Font("VNI-Centur", 1, 30));
            fonts.add(new Font("DT-Brookly", 1, 30));
        }
        //        fonts.add(loadFont("BINHLBI.TTF"));
        RenderingHints localRenderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        localRenderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        localGraphics2D.setRenderingHints(localRenderingHints);
        localGraphics2D.fillRect(0, 0, width, height);
        localGraphics2D.setColor(new Color(50, 50, 50));
        Random localRandom = new Random();
        int i = 0;
        int j = 0;
        for (int k = 0; k < CaptchaText.length(); k++) {
            i += 25 + Math.abs(localRandom.nextInt()) % 5;
            j = 25 + Math.abs(localRandom.nextInt()) % 20;
            int tmp = localRandom.nextInt(fonts.size() - 1);
            localGraphics2D.setFont(fonts.get(tmp));

            localGraphics2D.drawChars(CaptchaText.toCharArray(), k, 1, i, j);
        }
        localBufferedImage = getDistortedImage(localBufferedImage);
        Graphics2D localGraphics2D2 = localBufferedImage.createGraphics();
        localGraphics2D2.setRenderingHints(localRenderingHints);
        //        localGraphics2D2.fillRect(0, 0, width, height);
        localGraphics2D2.setColor(new Color(50, 50, 50));
        CubicCurve2D c = new CubicCurve2D.Double();// draw QuadCurve2D.Float with set coordinates
        for (int l = 0; l < 7; l++) {
            int x1 = Util.rand(0, width / 2);
            ;
            int x2 = Util.rand(width / 2, width);
            int y1 = Util.rand(0, height);
            int y2 = Util.rand(0, height);
            int ctrlx1 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly1 = y1;
            int ctrlx2 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly2 = y2;

            c.setCurve(x1, y1, ctrlx2, ctrly2, ctrlx1, ctrly1, x2, y2);
            localGraphics2D2.draw(c);
            //            localGraphics2D2.drawLine(randomX1(), randomY1(), randomX2(), randomY2());
        }

        localGraphics2D.dispose();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
    return localBufferedImage;
}

From source file:wsserver.EKF1TimerSessionBean.java

private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();

    return resizedImage;
}

From source file:lucee.runtime.img.Image.java

public void translate(int xtrans, int ytrans, Object interpolation) throws ExpressionException {

    RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, interpolation);
    if (interpolation != RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
        hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(1)));
    }/*  w  ww. j  a  v a  2 s . c o m*/

    ParameterBlock pb = new ParameterBlock();
    pb.addSource(image());
    BufferedImage img = JAI.create("translate", pb).getAsBufferedImage();
    Graphics2D graphics = img.createGraphics();
    graphics.clearRect(0, 0, img.getWidth(), img.getHeight());
    AffineTransform at = new AffineTransform();
    at.setToIdentity();
    graphics.drawImage(image(), new AffineTransformOp(at, hints), xtrans, ytrans);
    graphics.dispose();
    image(img);
}

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

/**
 * Create a back cover//from   w w  w  .  jav  a  2  s.  co m
 * 
 * @param coverId
 * @param titleStr
 * @param textColor
 * @param width
 * @param height
 * @param type
 * @param imgFormat
 * @param macColors
 *            - for PNG images reduce the color palette (must be greater
 *            than 2)
 * @return
 * @throws Exception
 */
public byte[] createBackCover(String coverId, String titleStr, String spineColor, String textColor, int width,
        int height, int type, ImageFormat imgFormat, int maxColors) throws Exception {

    Graphics2D g2D = null;

    try {
        // Front cover first
        // Read in base cover image
        BufferedImage coverImg = Imaging.getBufferedImage(coverMap.get(coverId));

        // Resize cover image to the basic 300 X 400 for front cover
        BufferedImage backCoverImg = resize(coverImg, 300, 400, type);
        g2D = (Graphics2D) backCoverImg.getGraphics();

        // Add title if present
        if (titleStr != null && titleStr.length() > 0) {
            BufferedImage titleTextImg = createText(82, 220, titleStr, textColor, true, backTitleFontMap, type);
            g2D.drawImage(titleTextImg, 40, 35, null);
        }

        // Add spine if present
        if (spineColor != null && spineColor.length() > 0) {
            g2D.setColor(Color.decode(spineColor));
            g2D.fillRect(backCoverImg.getWidth() - 2, 0, 2, backCoverImg.getHeight());
        }

        // If the requested size is not 300X400 convert the image
        BufferedImage outImg = null;
        if (width != 300 || height != 400) {
            outImg = resize(backCoverImg, width, height, type);
        } else {
            outImg = backCoverImg;
        }

        // Do we want a PNG with a fixed number of colors
        if (maxColors >= 2 && imgFormat == ImageFormat.IMAGE_FORMAT_PNG) {
            outImg = ImageUtils.reduce32(outImg, maxColors);
        }

        // Return bytes
        Map<String, Object> params = new HashMap<String, Object>();
        byte[] outBytes = Imaging.writeImageToBytes(outImg, imgFormat, params);
        return outBytes;
    } finally {
        if (g2D != null) {
            g2D.dispose();
        }
    }
}

From source file:jhplot.HChart.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.// w w  w. ja v  a2s  .  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(getCanvasPanel(), 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();
    }

}