Example usage for java.awt Graphics drawImage

List of usage examples for java.awt Graphics drawImage

Introduction

In this page you can find the example usage for java.awt Graphics drawImage.

Prototype

public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer);

Source Link

Document

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

Usage

From source file:com.google.code.facebook.graph.sna.applet.GraphZoomScrollPaneDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoom features./*w  ww  . j  a va 2  s  . co  m*/
 * 
 */
public GraphZoomScrollPaneDemo() {

    // create a simple graph for the demo
    graph = new DirectedSparseGraph<String, Number>();
    String[] v = createVertices(10);
    createEdges(v);

    ImageIcon sandstoneIcon = null;
    String imageLocation = "/images/Sandstone.jpg";
    try {
        sandstoneIcon = new ImageIcon(getClass().getResource(imageLocation));
    } catch (Exception ex) {
        System.err.println("Can't load \"" + imageLocation + "\"");
    }
    final ImageIcon icon = sandstoneIcon;
    vv = new VisualizationViewer<String, Number>(new KKLayout<String, Number>(graph));

    if (icon != null) {
        vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {
            public void paint(Graphics g) {
                Dimension d = vv.getSize();
                g.drawImage(icon.getImage(), 0, 0, d.width, d.height, vv);
            }

            public boolean useTransform() {
                return false;
            }
        });
    }
    vv.addPostRenderPaintable(new VisualizationViewer.Paintable() {
        int x;
        int y;
        Font font;
        FontMetrics metrics;
        int swidth;
        int sheight;
        String str = "GraphZoomScrollPane Demo";

        public void paint(Graphics g) {
            Dimension d = vv.getSize();
            if (font == null) {
                font = new Font(g.getFont().getName(), Font.BOLD, 30);
                metrics = g.getFontMetrics(font);
                swidth = metrics.stringWidth(str);
                sheight = metrics.getMaxAscent() + metrics.getMaxDescent();
                x = (d.width - swidth) / 2;
                y = (int) (d.height - sheight * 1.5);
            }
            g.setFont(font);
            Color oldColor = g.getColor();
            g.setColor(Color.lightGray);
            g.drawString(str, x, y);
            g.setColor(oldColor);
        }

        public boolean useTransform() {
            return false;
        }
    });

    vv.addGraphMouseListener(new TestGraphMouseListener<String>());
    vv.getRenderer().setVertexRenderer(new GradientVertexRenderer<String, Number>(Color.white, Color.red,
            Color.white, Color.blue, vv.getPickedVertexState(), false));
    vv.getRenderContext().setEdgeDrawPaintTransformer(new ConstantTransformer(Color.lightGray));
    vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray));
    vv.getRenderContext().setArrowDrawPaintTransformer(new ConstantTransformer(Color.lightGray));

    // add my listeners for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());
    vv.setEdgeToolTipTransformer(new Transformer<Number, String>() {
        public String transform(Number edge) {
            return "E" + graph.getEndpoints(edge).toString();
        }
    });

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderer().getVertexLabelRenderer().setPositioner(new InsidePositioner());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);
    vv.setForeground(Color.lightGray);

    // create a frome to hold the graph
    final JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse<String, Number>();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());
    vv.setToolTipText("<html><center>Type 'p' for Pick mode<p>Type 't' for Transform mode");

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    content.add(controls, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

From source file:edu.uci.ics.jung.samples.GraphZoomScrollPaneDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoom features.//from w  w  w. j a  va  2s.co  m
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public GraphZoomScrollPaneDemo() {

    // create a simple graph for the demo
    graph = new DirectedSparseGraph<String, Number>();
    String[] v = createVertices(10);
    createEdges(v);

    ImageIcon sandstoneIcon = null;
    String imageLocation = "/images/Sandstone.jpg";
    try {
        sandstoneIcon = new ImageIcon(getClass().getResource(imageLocation));
    } catch (Exception ex) {
        System.err.println("Can't load \"" + imageLocation + "\"");
    }
    final ImageIcon icon = sandstoneIcon;
    vv = new VisualizationViewer<String, Number>(new KKLayout<String, Number>(graph));

    if (icon != null) {
        vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {
            public void paint(Graphics g) {
                Dimension d = vv.getSize();
                g.drawImage(icon.getImage(), 0, 0, d.width, d.height, vv);
            }

            public boolean useTransform() {
                return false;
            }
        });
    }
    vv.addPostRenderPaintable(new VisualizationViewer.Paintable() {
        int x;
        int y;
        Font font;
        FontMetrics metrics;
        int swidth;
        int sheight;
        String str = "GraphZoomScrollPane Demo";

        public void paint(Graphics g) {
            Dimension d = vv.getSize();
            if (font == null) {
                font = new Font(g.getFont().getName(), Font.BOLD, 30);
                metrics = g.getFontMetrics(font);
                swidth = metrics.stringWidth(str);
                sheight = metrics.getMaxAscent() + metrics.getMaxDescent();
                x = (d.width - swidth) / 2;
                y = (int) (d.height - sheight * 1.5);
            }
            g.setFont(font);
            Color oldColor = g.getColor();
            g.setColor(Color.lightGray);
            g.drawString(str, x, y);
            g.setColor(oldColor);
        }

        public boolean useTransform() {
            return false;
        }
    });

    vv.addGraphMouseListener(new TestGraphMouseListener<String>());
    vv.getRenderer().setVertexRenderer(new GradientVertexRenderer<String, Number>(Color.white, Color.red,
            Color.white, Color.blue, vv.getPickedVertexState(), false));
    vv.getRenderContext().setEdgeDrawPaintTransformer(new ConstantTransformer(Color.lightGray));
    vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray));
    vv.getRenderContext().setArrowDrawPaintTransformer(new ConstantTransformer(Color.lightGray));

    // add my listeners for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());
    vv.setEdgeToolTipTransformer(new Transformer<Number, String>() {
        public String transform(Number edge) {
            return "E" + graph.getEndpoints(edge).toString();
        }
    });

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderer().getVertexLabelRenderer().setPositioner(new InsidePositioner());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);
    vv.setForeground(Color.lightGray);

    // create a frome to hold the graph
    final JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse<String, Number>();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());
    vv.setToolTipText("<html><center>Type 'p' for Pick mode<p>Type 't' for Transform mode");

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    content.add(controls, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

From source file:org.dd4t.mvc.controllers.AbstractBinaryController.java

private void fillResponse(final HttpServletRequest request, final HttpServletResponse response,
        final Binary binary, final String path, int resizeToWidth) throws IOException {
    InputStream content = null;/* www  . j  av a2  s. c o  m*/

    try {
        final long contentLength;
        if (isUseBinaryStorage()) {
            // Check last modified dates
            File binaryFile = new File(path);
            if (!binaryFile.exists() || binary.getLastPublishedDate().isAfter(binaryFile.lastModified())) {
                if (resizeToWidth == -1) {
                    saveBinary(binary, binaryFile);
                } else {
                    File tempBinary = new File(path + ".tmp");
                    saveBinary(binary, tempBinary);
                    content = new FileInputStream(tempBinary);
                    BufferedImage before = ImageIO.read(content);
                    int w = before.getWidth();
                    int h = before.getHeight();
                    float factor = (float) resizeToWidth / w;
                    int newH = Math.round(factor * h);

                    BufferedImage after = new BufferedImage(resizeToWidth, newH, BufferedImage.TYPE_INT_RGB);
                    Graphics g = after.createGraphics();
                    g.drawImage(before, 0, 0, resizeToWidth, newH, null);
                    g.dispose();

                    ImageIO.write(after, getImageType(path), binaryFile);
                }
            }
            content = new FileInputStream(binaryFile);
            contentLength = binaryFile.length();
        } else {
            content = binary.getBinaryData().getInputStream();
            contentLength = binary.getBinaryData().getDataSize();
        }

        response.setContentType(getContentType(binary, path, request));
        response.setHeader(CONTENT_LENGTH, Long.toString(contentLength));
        response.setHeader(LAST_MODIFIED, createDateFormat().format(binary.getLastPublishedDate().toDate()));
        response.setStatus(HttpStatus.OK.value());

        // Write binary data to output stream
        byte[] buffer = new byte[response.getBufferSize()];
        int len;
        while ((len = content.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException e) {
                LOG.error("Failed to close binary input stream", e);
            }
        }
    }
}

From source file:ScaleTest_2008.java

/**
 * Progressive bilinear scaling: for any downscale size, scale
 * iteratively by halves using BILINEAR filtering until the proper 
 * size is reached./*from  w  w  w.ja  v  a2s .c  o  m*/
 */
private BufferedImage getOptimalScalingImage(BufferedImage inputImage, int startSize, int endSize) {
    int currentSize = startSize;
    BufferedImage currentImage = inputImage;
    int delta = currentSize - endSize;
    int nextPow2 = currentSize >> 1;
    while (currentSize > 1) {
        if (delta <= nextPow2) {
            if (currentSize != endSize) {
                BufferedImage tmpImage = new BufferedImage(endSize, endSize, BufferedImage.TYPE_INT_RGB);
                Graphics g = tmpImage.getGraphics();
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), tmpImage.getHeight(), null);
                currentImage = tmpImage;
            }
            return currentImage;
        } else {
            BufferedImage tmpImage = new BufferedImage(currentSize >> 1, currentSize >> 1,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tmpImage.getGraphics();
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), tmpImage.getHeight(), null);
            currentImage = tmpImage;
            currentSize = currentImage.getWidth();
            delta = currentSize - endSize;
            nextPow2 = currentSize >> 1;
        }
    }
    return currentImage;
}

From source file:se.llbit.chunky.renderer.test.TestRenderer.java

@Override
public void drawBufferedImage(Graphics g, int width, int height) {
    synchronized (backBuffer) {
        g.drawImage(backBuffer, 0, 0, width, height, null);
    }/*from w  ww. jav  a  2 s  .  c  om*/
}

From source file:se.llbit.chunky.renderer.cl.CLRenderManager.java

@Override
public void drawBufferedImage(Graphics g, int width, int height) {
    synchronized (buffer) {
        g.drawImage(buffer, 0, 0, width, height, null);
    }//w ww . j  av a 2 s .co  m
}

From source file:org.jas.dnd.DragTooltipDialog.java

public void setContent(final Picture picture) {
    jContentPane.setName(DRAG_DIALOG_NAME);
    final Dimension d = calculateImagePanelSize(picture);
    final int width = d.width;
    final int height = d.height;
    JPanel imagePanel = new JPanel() {
        private static final long serialVersionUID = 1L;

        @Override// w w w.ja v a 2 s .  c o m
        protected void paintComponent(Graphics g) {
            g.drawImage(picture.getImage(), 0, 0, width, height, null);
        }
    };
    descriptionPanel.setBounds(7, 20, width, height);
    descriptionPanel.add(imagePanel);
    this.setFullSize(width + 14, height + dragIcon.getHeight() + 7);
    TransparencyManagerFactory.getManager().setWindowOpaque(this, false);
}

From source file:net.bioclipse.model.ScatterPlotMouseHandler.java

@Override
public void mouseDragged(MouseEvent e) {
    super.mouseDragged(e);

    ChartPanel chartPanel = getChartPanel(e);
    JFreeChart selectedChart = chartPanel.getChart();
    ChartDescriptor cd = ChartUtils.getChartDescriptor(selectedChart);
    int[] indices = cd.getSourceIndices();

    XYPlot plot = (XYPlot) chartPanel.getChart().getPlot();

    //Create double buffer
    Image buffer = chartPanel.createImage(chartPanel.getWidth(), chartPanel.getHeight());
    Graphics bufferGraphics = buffer.getGraphics();
    chartPanel.paint(bufferGraphics);//from w w w. j a va  2  s  .c  om

    if (lastX == 0 && lastY == 0) {
        lastX = e.getX();
        lastY = e.getY();
    }

    drawRect = new Rectangle();
    int x1 = Math.min(Math.min(e.getX(), lastX), startX);
    int y1 = Math.min(Math.min(e.getY(), lastY), startY);
    int x2 = Math.max(Math.max(e.getX(), lastX), startX);
    int y2 = Math.max(Math.max(e.getY(), lastY), startY);

    drawRect.x = x1;
    drawRect.y = y1;
    drawRect.width = x2 - drawRect.x;
    drawRect.height = y2 - drawRect.y;

    //Create a clipping rectangle
    Rectangle clipRect = new Rectangle(drawRect.x - 100, drawRect.y - 100, drawRect.width + 200,
            drawRect.height + 200);

    //Check for selected points
    for (int j = 0; j < plot.getDataset().getItemCount(plot.getDataset().getSeriesCount() - 1); j++) {
        for (int i = 0; i < plot.getDataset().getSeriesCount(); i++) {
            Number xK = plot.getDataset().getX(i, j);
            Number yK = plot.getDataset().getY(i, j);
            Point2D datasetPoint2D = new Point2D.Double(domainValueTo2D(chartPanel, plot, xK.doubleValue()),
                    rangeValueTo2D(chartPanel, plot, yK.doubleValue()));

            if (drawRect.contains(datasetPoint2D)) {
                PlotPointData cp = new PlotPointData(indices[j], cd.getXLabel(), cd.getYLabel());
                boolean pointAdded = mouseDragSelection.addPoint(cp);
                if (pointAdded) {
                    ((ScatterPlotRenderer) plot.getRenderer()).addMarkedPoint(j, i);
                    selectedChart.plotChanged(new PlotChangeEvent(plot));
                }
            } else if (!mouseDragSelection.isEmpty()) {
                PlotPointData cp = new PlotPointData(indices[j], cd.getXLabel(), cd.getYLabel());
                boolean pointRemoved = mouseDragSelection.removePoint(cp);
                if (pointRemoved) {
                    ((ScatterPlotRenderer) plot.getRenderer()).removeMarkedPoint(new Point(j, i));
                    selectedChart.plotChanged(new PlotChangeEvent(plot));
                }
            }
        }
    }

    Iterator<PlotPointData> iterator = currentSelection.iterator();
    while (iterator.hasNext()) {
        PlotPointData next = iterator.next();
        Point dataPoint = next.getDataPoint();
        ((ScatterPlotRenderer) plot.getRenderer()).addMarkedPoint(dataPoint);
    }

    lastX = e.getX();
    lastY = e.getY();

    Graphics graphics = chartPanel.getGraphics();
    graphics.setClip(clipRect);

    //Draw selection rectangle
    bufferGraphics.drawRect(drawRect.x, drawRect.y, drawRect.width, drawRect.height);

    graphics.drawImage(buffer, 0, 0, chartPanel.getWidth(), chartPanel.getHeight(), null);
}

From source file:org.esa.s1tbx.ocean.toolviews.polarview.polarplot.PolarCanvas.java

private void drawColorBar(Graphics g, Axis cAxis) {
    final Dimension cbSize = new Dimension((int) (graphSize.width * 0.03),
            (int) (Math.min(200, graphSize.height * 0.6)));
    final Point at = new Point(20, -30);

    g.translate(at.x, at.y);/*from   ww  w .java  2s .com*/
    g.drawImage(colorBar, 0, 0, cbSize.width, cbSize.height, this);
    g.drawRect(0, 0, cbSize.width, cbSize.height);
    g.translate(cbSize.width, cbSize.height);
    cAxis.draw(g, cbSize);
    g.drawString(cAxis.getUnit(), 50, 5);
    g.translate(-cbSize.width - at.x, -cbSize.height - at.y);
}

From source file:org.esa.nest.dat.views.polarview.PolarCanvas.java

private void drawColorBar(Graphics g, Axis cAxis) {
    final Dimension cbSize = new Dimension((int) (graphSize.width * 0.03),
            (int) (Math.min(200, graphSize.height * 0.6)));
    final Point at = new Point(20, -100);

    g.translate(at.x, at.y);//  ww  w . j  a  v a2 s  .c om
    g.drawImage(colorBar, 0, 0, cbSize.width, cbSize.height, this);
    g.drawRect(0, 0, cbSize.width, cbSize.height);
    g.translate(cbSize.width, cbSize.height);
    cAxis.draw(g, cbSize);
    g.drawString(cAxis.getUnit(), 50, 5);
    g.translate(-cbSize.width - at.x, -cbSize.height - at.y);
}