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.funambol.foundation.util.MediaUtils.java

/**
 * Rotates given buffered image by given amount of degree.
 * The valid degree values are 0, 90, 180, 270.
 * If the image is a jpg, the rotation is lossless, exif data are preserved
 * and image size is almost the same./*w  ww.  j a  v  a  2s .co  m*/
 *
 * @param bufImage the buffered image
 * @param degree amount of degree to apply
 * @return a buffered image containing rotated image data
 * @throws PicturesException if amount of degree is invalid or if an
 *         IOException occurs
 */
private static BufferedImage rotateImage(BufferedImage bufImage, int degree)
        throws FileDataObjecyUtilsException {

    degree = degree % 360;
    int h;
    int w;

    switch (degree) {
    case 0:
    case 180:
        h = bufImage.getHeight();
        w = bufImage.getWidth();
        break;
    case 90:
    case 270:
        h = bufImage.getWidth();
        w = bufImage.getHeight();
        break;
    default:
        throw new FileDataObjecyUtilsException(
                "Error rotating image since the '" + degree + "' degree value is unsupported");
    }

    BufferedImage out = null;

    int bufImageType = bufImage.getType();
    if (BufferedImage.TYPE_BYTE_INDEXED == bufImageType || BufferedImage.TYPE_BYTE_BINARY == bufImageType) {

        IndexColorModel model = (IndexColorModel) bufImage.getColorModel();
        out = new BufferedImage(w, h, bufImage.getType(), model);

    } else if (BufferedImage.TYPE_CUSTOM == bufImageType) {

        // we don't know what type of image it can be

        // there's a bug in some VM that cause some PNG images to have 
        // type custom: this should take care of this issue

        //check if we need to have alpha channel
        boolean alpha = bufImage.getTransparency() != BufferedImage.OPAQUE;

        if (alpha) {
            // TYPE_INT_ARGB_PRE gives you smaller output images
            // than TYPE_INT_ARGB
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
        } else {
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        }

    } else {

        out = new BufferedImage(w, h, bufImage.getType());
    }

    Graphics2D g2d = out.createGraphics();

    Map renderingHints = new HashMap();

    renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

    g2d.setRenderingHints(renderingHints);
    g2d.rotate(Math.toRadians(degree));

    switch (degree) {
    case 90:
        g2d.translate(0, -w);
        break;
    case 180:
        g2d.translate(-w, -h);
        break;
    case 270:
        g2d.translate(-h, 0);
        break;
    }

    g2d.drawImage(bufImage, null, 0, 0);
    g2d.dispose();

    return out;
}

From source file:Main.java

public void drawImage() {
    Graphics2D g = img.createGraphics();
    RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHints(hints);//ww  w .  j  a  v  a2 s . c  o m

    g.setStroke(new BasicStroke(4));
    for (Ellipse2D shape : shapes) {
        g.setColor(Color.blue);
        g.fill(shape);
        if (shape.contains(mouse)) {
            g.setColor(Color.RED);
        } else {
            g.setColor(Color.YELLOW);
        }
        g.draw(shape);
    }

    l.setIcon(new ImageIcon(img));

    g.dispose();
}

From source file:com.sketchy.image.ImageProcessingThread.java

public static BufferedImage resizeImage(BufferedImage image, int drawingWidth, int drawingHeight,
        CenterOption centerOption, ScaleOption scaleOption) {

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    double widthScale = drawingWidth / (double) imageWidth;
    double heightScale = drawingHeight / (double) imageHeight;
    double scale = Math.min(widthScale, heightScale);

    int scaleWidth = (int) (imageWidth * scale);
    int scaleHeight = (int) (imageHeight * scale);

    BufferedImage resizedImage = new BufferedImage(scaleWidth, scaleHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = resizedImage.createGraphics();

    if (scaleOption == ScaleOption.SCALE_AREA_AVERAGING) {
        ImageProducer prod = new FilteredImageSource(image.getSource(),
                new AreaAveragingScaleFilter(scaleWidth, scaleHeight));
        Image img = Toolkit.getDefaultToolkit().createImage(prod);
        g.drawImage(img, 0, 0, scaleWidth, scaleHeight, null); // it's already scaled
    } else {/* w  w w.  j  a  va 2s .c  om*/
        if (scaleOption == ScaleOption.SCALE_NEAREST_NEIGHBOR) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        } else if (scaleOption == ScaleOption.SCALE_BICUBIC) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        } else if (scaleOption == ScaleOption.SCALE_BILINEAR) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
        g.drawImage(image, 0, 0, scaleWidth, scaleHeight, 0, 0, imageWidth, imageHeight, null);
    }
    g.dispose();

    int cropWidth = (int) Math.min(scaleWidth, drawingWidth);
    int cropHeight = (int) Math.min(scaleHeight, drawingHeight);

    int drawingLeft = 0;
    int drawingTop = 0;
    if ((centerOption == CenterOption.CENTER_HORIZONTAL) || (centerOption == CenterOption.CENTER_BOTH)) {
        drawingLeft = (int) ((drawingWidth - cropWidth) / 2.0);
    }
    if ((centerOption == CenterOption.CENTER_VERTICAL) || (centerOption == CenterOption.CENTER_BOTH)) {
        drawingTop = (int) ((drawingHeight - cropHeight) / 2.0);
    }

    BufferedImage croppedImage = resizedImage.getSubimage(0, 0, cropWidth, cropHeight);
    resizedImage = null;

    BufferedImage drawingImage = new BufferedImage(drawingWidth, drawingHeight, BufferedImage.TYPE_INT_ARGB);
    g = drawingImage.createGraphics();
    g.drawImage(croppedImage, drawingLeft, drawingTop, drawingLeft + cropWidth, drawingTop + cropHeight, 0, 0,
            cropWidth, cropHeight, null);
    g.dispose();

    croppedImage = null;
    return drawingImage;
}

From source file:krasa.cpu.CpuUsagePanel.java

/**
 * it will probably be better synchronized, not sure
 *//* w ww .  j av  a2 s . c o m*/
private synchronized void draw(Graphics g, Image bufferedImage) {
    UIUtil.drawImage(g, bufferedImage, 0, 0, null);
    if (UIUtil.isJreHiDPI((Graphics2D) g) && !UIUtil.isUnderDarcula()) {
        Graphics2D g2 = (Graphics2D) g.create(0, 0, getWidth(), getHeight());
        float s = JBUI.sysScale(g2);
        g2.scale(1 / s, 1 / s);
        g2.setColor(UIUtil.isUnderIntelliJLaF() ? Gray.xC9 : Gray.x91);
        g2.drawLine(0, 0, (int) (s * getWidth()), 0);
        g2.scale(1, 1);
        g2.dispose();
    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

/**
 * Draws a scale used with the heat map/*from   www  .  j a va2 s.  co  m*/
 * @param output
 * @param valueRange
 * @param width
 * @param height
 * @throws IOException
 */
private static void drawVerticalScale(Path output, double min, double max, int width, int height,
        OperationsParams params) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    // fix this part to work according to color1, color2 and gradient type
    HDFPlot.HDFRasterizer gradient = new HDFPlot.HDFRasterizer();
    gradient.configure(params);
    HDFRasterLayer gradientLayer = (HDFRasterLayer) gradient.createCanvas(0, 0, new Rectangle());
    for (int y = 0; y < height; y++) {
        Color color = gradientLayer.calculateColor(height - y, 0, height);
        g.setColor(color);
        g.drawRect(width * 3 / 4, y, width / 4, 1);
    }

    int fontSize = 24;
    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    double step = (max - min) * fontSize * 5 / height;
    step = (int) (Math.pow(10.0, Math.round(Math.log10(step))));
    double min_value = Math.floor(min / step) * step;
    double max_value = Math.floor(max / step) * step;

    g.setColor(Color.WHITE);
    for (double value = min_value; value <= max_value; value += step) {
        double y = ((value - min) + (max - value) * (height - fontSize)) / (max - min);
        g.drawString(String.valueOf((int) value), 5, (int) y);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

/**
 * Draws a scale used with the heat map/*from w  ww  .  jav  a 2s  .com*/
 * @param output
 * @param valueRange
 * @param width
 * @param height
 * @throws IOException
 */
private static void drawHorizontalScale(Path output, double min, double max, int width, int height,
        OperationsParams params) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    int fontSize = 24;
    // fix this part to work according to color1, color2 and gradient type
    HDFPlot.HDFRasterizer gradient = new HDFPlot.HDFRasterizer();
    gradient.configure(params);
    HDFRasterLayer gradientLayer = (HDFRasterLayer) gradient.createCanvas(0, 0, new Rectangle());
    for (int x = 0; x < width; x++) {
        Color color = gradientLayer.calculateColor(x, 0, width);
        g.setColor(color);
        g.drawRect(x, height - (fontSize - 5), 1, fontSize - 5);
    }

    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    double step = (max - min) * fontSize * 5 / width;
    step = (int) (Math.pow(10.0, Math.round(Math.log10(step))));
    double min_value = Math.floor(min / step) * step;
    double max_value = Math.floor(max / step) * step;

    g.setColor(Color.WHITE);
    for (double value = min_value; value <= max_value; value += step) {
        double x = ((value - min) * (width - fontSize) + (max - value)) / (max - min);
        g.drawString(String.valueOf((int) value), (int) x, fontSize);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:com.skcraft.launcher.swing.InstanceTableModel.java

private ImageIcon buildDownloadIcon(BufferedImage instanceIcon) {
    try {//www. j  a  va 2s. c o m
        BufferedImage iconBg = instanceIcon;
        BufferedImage iconFg = ImageIO.read(Launcher.class.getResource("download_icon_overlay.png"));
        BufferedImage iconCombined = new BufferedImage(iconBg.getWidth(), iconBg.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D canvas = iconCombined.createGraphics();
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        canvas.drawImage(iconBg, 0, 0, null);
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        canvas.drawImage(iconFg, iconBg.getWidth() - iconFg.getWidth(), iconBg.getHeight() - iconFg.getHeight(),
                null);
        canvas.dispose();
        return new ImageIcon(iconCombined);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.deegree.test.gui.StressTestController.java

private void renderResizedImage(HttpServletResponse response, String shot, int width, int height)
        throws IOException {
    BufferedImage originalImage = ImageIO.read(new File(shot));

    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = scaledImage.createGraphics();
    graphics.setComposite(AlphaComposite.Src);
    graphics.drawImage(originalImage, 0, 0, width, height, null);
    graphics.dispose();

    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    ImageIO.write(scaledImage, "jpg", out);
    out.close();/*from  w  w  w. j a  v  a2  s  . c o m*/

}

From source file:Servlet3.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//ww  w  .  j av  a2  s  .  co m
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        // To Insert data to UserActivity table for Recent Activities Tab
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);
        // To insert colored Pie Chart into the PDF file using
        // iText now   
        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();

            PieChart.addTitle("Pie-Chart");
            PieChart.addAuthor("MUurugappan");

            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();

            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set response headers to view PDF
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}

From source file:common.utils.ImageUtils.java

/**
 *
 * @param src images to draw, they must be resized to an appropriate size
 * @param dst image where given images will be drawen
 *//*from w  w  w .j  a va 2s .c o m*/
public static void draw4on1(BufferedImage[] src, BufferedImage dst) {
    Graphics2D g2 = dst.createGraphics();
    g2.setColor(java.awt.Color.WHITE);
    g2.fillRect(0, 0, dst.getWidth(), dst.getHeight());
    int dxi;
    int dyi = 0;

    int x0 = dst.getWidth() - 5;
    int y0 = 5;
    int x = x0;
    int y = y0;
    for (int i = 0; i < src.length; i++) {
        if (i % 2 == 0) {
            dxi = -10;
        } else {
            dxi = 0;
        }
        //g2.draw3DRect(dx - 1 , dy-tmp_bi.getHeight() - 1, tmp_bi.getWidth() + 1 , tmp_bi.getHeight() + 1, true);
        g2.drawImage(src[i], x - src[i].getWidth() + dxi, y + dyi, null);
        g2.drawString("#" + i, x - src[i].getWidth() + dxi, y + dyi + 20);
        //g2.rotate(Math.toRadians(4));
        y = y + src[i].getHeight() / 2;
        if (y > dst.getHeight() - src[i].getHeight()) {
            y = y0;
            if (dyi == 0)
                dyi = 10;
            else
                dyi = 0;
            if (x < src[i].getWidth()) {
                x = dst.getWidth();
            }
            x = x - src[i].getWidth() / 2;
        }
    }
    g2.setColor(Color.gray);
    g2.drawRect(0, 0, dst.getWidth() - 1, dst.getHeight() - 1);
    g2.dispose();
}