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, ImageObserver observer);

Source Link

Document

Draws as much of the specified image as is currently available.

Usage

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Builds an image layer of all the layers in a SavedMap.
 * /*from w  w w  .j av  a2  s  .  com*/
 * @mapWidth
 * @mapHeight
 */
private BufferedImage getLegendExportCanvas(int mapWidth, int mapHeight) {
    int padding = 2;
    BufferedImage base = null;
    Graphics mapBaseGraphic = null;
    Color innerBackgroundColor = Color.darkGray;
    Color outerBorderColor = Color.black;
    int legendTopPlacement = 0;
    int legendLeftPlacement = 0;
    int widestLegend = 0;
    int legendXPosition = 0;
    int legendYPosition = 0;

    List<? extends DashboardLayer> layers = this.getAllHasLayer().getAll();

    try {
        base = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
        mapBaseGraphic = base.getGraphics();
        mapBaseGraphic.drawImage(base, 0, 0, null);

        // Generates map overlays and combines them into a single map image
        for (DashboardLayer layer : layers) {
            if (layer.getDisplayInLegend()) {
                Graphics2D titleBaseGraphic = null;
                Graphics2D iconGraphic = null;

                String requestURL = getLegendURL(layer);

                try {
                    // handle color graphics and categories
                    BufferedImage titleBase = getLegendTitleImage(layer);
                    titleBaseGraphic = titleBase.createGraphics();
                    int paddedTitleWidth = titleBase.getWidth();
                    int paddedTitleHeight = titleBase.getHeight();

                    BufferedImage icon = getImageFromGeoserver(requestURL);
                    int iconHeight = icon.getHeight();
                    int iconWidth = icon.getWidth();
                    int paddedIconWidth = iconWidth + (padding * 2);
                    int paddedIconHeight = iconHeight + (padding * 2);

                    int fullWidth = paddedIconWidth + paddedTitleWidth;
                    int fullHeight;
                    if (paddedIconHeight >= paddedTitleHeight) {
                        fullHeight = paddedIconHeight;
                    } else {
                        fullHeight = paddedTitleHeight;
                    }

                    DashboardLegend legend = layer.getDashboardLegend();
                    if (legend.getGroupedInLegend()) {
                        if (legendTopPlacement + fullHeight >= mapHeight) {
                            legendLeftPlacement = widestLegend + legendLeftPlacement + padding;
                            legendTopPlacement = 0; // reset so 2nd column legends start at the top row
                        }
                        legendXPosition = legendLeftPlacement + padding;
                        legendYPosition = legendTopPlacement + padding;
                    } else {
                        legendXPosition = (int) Math.round((double) legend.getLegendXPosition());
                        legendYPosition = (int) Math.round((double) legend.getLegendYPosition());
                    }

                    BufferedImage legendBase = new BufferedImage(fullWidth + (padding * 2),
                            fullHeight + (padding * 2), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D legendBaseGraphic = legendBase.createGraphics();
                    legendBaseGraphic.setColor(innerBackgroundColor);
                    legendBaseGraphic.fillRect(0, 0, fullWidth, fullHeight);
                    legendBaseGraphic.setColor(outerBorderColor);
                    legendBaseGraphic.setStroke(new BasicStroke(5));
                    legendBaseGraphic.drawRect(0, 0, fullWidth, fullHeight);

                    legendBaseGraphic.drawImage(icon, padding, padding, paddedIconWidth, paddedIconHeight,
                            null);
                    legendBaseGraphic.drawImage(titleBase, paddedIconWidth + (padding * 2),
                            (fullHeight / 2) - (paddedTitleHeight / 2), paddedTitleWidth, paddedTitleHeight,
                            null);
                    mapBaseGraphic.drawImage(legendBase, legendXPosition, legendYPosition, fullWidth,
                            fullHeight, null);

                    if (legend.getGroupedInLegend()) {
                        legendTopPlacement = legendTopPlacement + fullHeight + padding;
                    }

                    if (fullWidth > widestLegend) {
                        widestLegend = fullWidth;
                    }
                } finally {
                    if (titleBaseGraphic != null) {
                        titleBaseGraphic.dispose();
                    }

                    if (iconGraphic != null) {
                        iconGraphic.dispose();
                    }
                }
            }
        }
    } finally {
        mapBaseGraphic.dispose();
    }

    return base;
}

From source file:org.jas.gui.ImagePanel.java

@Override
protected void paintComponent(Graphics g) {
    if (portrait == null) {
        super.paintComponent(g);
        return;//from   w  w  w.j a  va2  s.  c  o m
    }
    try {
        // Create a translucent intermediate image in which we can perform the soft clipping
        GraphicsConfiguration gc = ((Graphics2D) g).getDeviceConfiguration();
        BufferedImage intermediateBufferedImage = gc.createCompatibleImage(getWidth(), getHeight(),
                Transparency.TRANSLUCENT);
        Graphics2D bufferGraphics = intermediateBufferedImage.createGraphics();

        // Clear the image so all pixels have zero alpha
        bufferGraphics.setComposite(AlphaComposite.Clear);
        bufferGraphics.fillRect(0, 0, getWidth(), getHeight());

        // Render our clip shape into the image. Shape on where to paint
        bufferGraphics.setComposite(AlphaComposite.Src);
        bufferGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        bufferGraphics.setColor(Color.WHITE);
        bufferGraphics.fillRoundRect(0, 0, getWidth(), getHeight(), (int) (getWidth() * arcWidth),
                (int) (getHeight() * arcHeight));

        // SrcAtop uses the alpha value as a coverage value for each pixel stored in the
        // destination shape. For the areas outside our clip shape, the destination
        // alpha will be zero, so nothing is rendered in those areas. For
        // the areas inside our clip shape, the destination alpha will be fully
        // opaque.
        bufferGraphics.setComposite(AlphaComposite.SrcAtop);
        bufferGraphics.drawImage(portrait, 0, 0, getWidth(), getHeight(), null);
        bufferGraphics.dispose();

        // Copy our intermediate image to the screen
        g.drawImage(intermediateBufferedImage, 0, 0, null);

    } catch (Exception e) {
        log.warn("Error: Creating Renderings", e);
    }
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Generate an image replicating the users map in the browser.
 * /*from   ww  w. j a va 2  s  .c  o m*/
 * @outFileFormat - Allowed types (png, gif, jpg, bmp)
 * @mapBounds - JSON constructed as {"bottom":"VALUE", "top":"VALUE", "left":"VALUE", "right":"VALUE"}
 * @mapSize - JSON constructed as {"width":"VALUE", "height":"VALUE"}
 * @activeBaseMap = JSON constructed as {"LAYER_SOURCE_TYPE":"VALUE"}
 */
@Override
public InputStream generateMapImageExport(String outFileFormat, String mapBounds, String mapSize,
        String activeBaseMap) {
    InputStream inStream = null;
    int width;
    int height;

    // Get dimensions of the map window (<div>)
    try {
        JSONObject mapSizeObj = new JSONObject(mapSize);
        width = mapSizeObj.getInt("width");
        height = mapSizeObj.getInt("height");
    } catch (JSONException e) {
        String error = "Could not parse map size.";
        throw new ProgrammingErrorException(error, e);
    }

    // Setup the base canvas to which we will add layers and map elements
    BufferedImage base = null;
    Graphics mapBaseGraphic = null;
    try {
        if (outFileFormat.toLowerCase().equals("png") || outFileFormat.toLowerCase().equals("gif")) {
            base = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        } else if (outFileFormat.equals("jpg") || outFileFormat.toLowerCase().equals("bmp")) {
            base = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        }

        // Create the base canvas that all other map elements will be draped on top of
        mapBaseGraphic = base.getGraphics();
        mapBaseGraphic.setColor(Color.white);
        mapBaseGraphic.fillRect(0, 0, width, height);
        mapBaseGraphic.drawImage(base, 0, 0, null);

        // Ordering the layers from the default map
        DashboardLayer[] orderedLayers = this.getOrderedLayers();

        // Add layers to the base canvas
        BufferedImage layerCanvas = getLayersExportCanvas(width, height, orderedLayers, mapBounds);

        // Get base map
        String baseType = null;
        try {
            JSONObject activeBaseObj = new JSONObject(activeBaseMap);
            baseType = activeBaseObj.getString("LAYER_SOURCE_TYPE");
        } catch (JSONException e) {
            String error = "Could not active base map JSON.";
            throw new ProgrammingErrorException(error, e);
        }

        // Get bounds of the map
        if (baseType.length() > 0) {
            String bottom;
            String top;
            String right;
            String left;
            try {
                JSONObject mapBoundsObj = new JSONObject(mapBounds);
                bottom = mapBoundsObj.getString("bottom");
                top = mapBoundsObj.getString("top");
                right = mapBoundsObj.getString("right");
                left = mapBoundsObj.getString("left");
            } catch (JSONException e) {
                String error = "Could not parse map bounds.";
                throw new ProgrammingErrorException(error, e);
            }

            BufferedImage baseMapImage = this.getBaseMapCanvas(width, height, left, bottom, right, top,
                    baseType);

            if (baseMapImage != null) {
                mapBaseGraphic.drawImage(baseMapImage, 0, 0, null);
            }
        }

        // Offset the layerCanvas so that it is center
        int widthOffset = (int) ((width - layerCanvas.getWidth()) / 2);
        int heightOffset = (int) ((height - layerCanvas.getHeight()) / 2);

        mapBaseGraphic.drawImage(layerCanvas, widthOffset, heightOffset, null);

        // Add legends to the base canvas
        BufferedImage legendCanvas = getLegendExportCanvas(width, height);
        mapBaseGraphic.drawImage(legendCanvas, 0, 0, null);
    } finally {
        ByteArrayOutputStream outStream = null;
        try {
            outStream = new ByteArrayOutputStream();
            ImageIO.write(base, outFileFormat, outStream);
            inStream = new ByteArrayInputStream(outStream.toByteArray());
        } catch (IOException e) {
            String error = "Could not write map image to the output stream.";
            throw new ProgrammingErrorException(error, e);
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    String error = "Could not close stream.";
                    throw new ProgrammingErrorException(error, e);
                }
            }
        }

        if (mapBaseGraphic != null) {
            mapBaseGraphic.dispose();
        }
    }

    return inStream;
}

From source file:se.llbit.chunky.renderer.scene.Scene.java

/**
 * Draw the buffered image to a canvas/*  w w  w . j av  a 2 s. c  om*/
 * @param g The graphics object of the canvas to draw on
 * @param canvasWidth The canvas width
 * @param canvasHeight The canvas height
 */
public synchronized void drawBufferedImage(Graphics g, int canvasWidth, int canvasHeight) {
    g.drawImage(buffer, 0, 0, null);
}

From source file:javazoom.jlgui.player.amp.Player.java

public void paint(Graphics g) {
    if (offScreenImage != null) {
        g.drawImage(offScreenImage, 0, 0, this);
    }
}

From source file:MyJava3D.java

public void paint(Graphics g) {
    Dimension d = getSize();// www.  j a v a 2 s  . c o m

    if (imageType == 1) {
        bimg = null;
        startClock();
    } else if (bimg == null || biw != d.width || bih != d.height) {
        if (animating != null && (biw != d.width || bih != d.height)) {
            animating.reset(d.width, d.height);
        }
        bimg = createBufferedImage(d.width, d.height, imageType - 2);
        clearOnce = true;
        startClock();
    }

    if (animating != null && animating.thread != null) {
        animating.step(d.width, d.height);
    }

    Graphics2D g2 = createGraphics2D(d.width, d.height, bimg, g);
    render(d.width, d.height, g2);
    g2.dispose();

    if (bimg != null) {
        g.drawImage(bimg, 0, 0, null);
        toolkit.sync();
    }
}

From source file:org.rdv.ui.TimeSlider.java

/**
 * Paint the components. Also paint the slider and the markers.
 *///  w  ww . j  a v  a  2s . c om
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Insets insets = getInsets();

    g.setColor(Color.lightGray);
    g.fillRect(insets.left + 6, insets.top + 4, getWidth() - insets.left - 12 - insets.right, 3);

    if (isEnabled()) {
        g.setColor(Color.gray);
        int startX = getXFromTime(start);
        int endX = getXFromTime(end);
        g.fillRect(startX, insets.top + 4, endX - startX, 3);
    }

    for (EventMarker marker : markers) {
        double markerTime = Double.parseDouble(marker.getProperty("timestamp"));
        if (markerTime >= minimum && markerTime <= maximum) {
            int x = getXFromTime(markerTime);
            if (x == -1) {
                continue;
            }

            Image markerImage;

            String markerType = marker.getProperty("type");
            if (markerType.compareToIgnoreCase("annotation") == 0) {
                markerImage = annotationMarkerImage;
            } else if (markerType.compareToIgnoreCase("start") == 0) {
                markerImage = startMarkerImage;
            } else if (markerType.compareToIgnoreCase("stop") == 0) {
                markerImage = stopMarkerImage;
            } else {
                markerImage = defaultMarkerImage;
            }

            g.drawImage(markerImage, x - 1, insets.top, null);
        }
    }
}

From source file:paquete.HollywoodUI.java

private void btn_add_graphicMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_graphicMouseClicked
    x_map = evt.getX();// w w w.j av  a 2 s. co  m
    y_map = evt.getY();
    System.out.println("Cordenada X: " + x_map);
    System.out.println("Cordeanda Y: " + y_map);
    Image image_actor = new ImageIcon("./src/sources/kevinBacon.jpg").getImage();
    Graphics g = label_grafico.getGraphics();
    g.drawImage(image_actor, CordenadaX[CordCont], CordenadaY[CordCont], label_grafico);
    System.out.println("CoordenadaX: " + CordenadaX[CordCont]);
    System.out.println("CoordenadaY: " + CordenadaY[CordCont]);
    CordCont++;
    add_actor_mapa.setVisible(false);

}

From source file:org.kalypso.ogc.gml.map.MapPanel.java

/**
 * Paints contents of the map in the following order:
 * <ul>/*from   w  w  w.  j  a va  2 s .  c  o  m*/
 * <li>the buffered image containing the layers</li>
 * <li>the status, if not OK</li>
 * <li>all 'paint-listeners'</li>
 * <li>the current widget</li>
 * </ul>
 * 
 * @see java.awt.Component#paint(java.awt.Graphics)
 */
@Override
public void paint(final Graphics g) {
    final int width = getWidth();
    final int height = getHeight();
    if (height == 0 || width == 0)
        return;

    // only recreate buffered image if size has changed
    if (m_imageBuffer == null || m_imageBuffer.getWidth() != width || m_imageBuffer.getHeight() != height)
        m_imageBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    else
        // this seems to be enough for clearing the image here
        m_imageBuffer.flush();

    Graphics2D bufferGraphics = null;
    try {
        bufferGraphics = m_imageBuffer.createGraphics();
        bufferGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        bufferGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        final BufferPaintJob bufferPaintJob = m_bufferPaintJob; // get copy (for more thread safety)
        if (bufferPaintJob != null) {
            paintBufferedMap(bufferGraphics, bufferPaintJob);
        }

        // TODO: at the moment, we paint the status just on top of the map, if we change this component to SWT, we should
        // show the statusComposite in a title bar, if the status is non-OK (with details button for a stack trace)
        paintStatus(bufferGraphics);

        final IMapPanelPaintListener[] pls = m_paintListeners.toArray(new IMapPanelPaintListener[] {});
        for (final IMapPanelPaintListener pl : pls)
            pl.paint(bufferGraphics);

        paintWidget(bufferGraphics);
    } finally {
        if (bufferGraphics != null)
            bufferGraphics.dispose();
    }

    if (m_isMultitouchEnabled) {
        final IMapPanelMTPaintListener[] postls = m_postPaintListeners
                .toArray(new IMapPanelMTPaintListener[] {});
        for (final IMapPanelMTPaintListener pl : postls)
            pl.paint(m_imageBuffer);
    } else {
        g.drawImage(m_imageBuffer, 0, 0, null);
    }
}

From source file:com.cburch.logisim.gui.start.AboutCredits.java

@Override
protected void paintComponent(Graphics g) {
    FontMetrics[] fms = new FontMetrics[font.length];
    for (int i = 0; i < fms.length; i++) {
        fms[i] = g.getFontMetrics(font[i]);
    }//  w  w w. j  a  v a 2  s.com
    if (linesHeight == 0) {
        int y = 0;
        int index = -1;
        for (CreditsLine line : lines) {
            index++;
            if (index == initialLines)
                initialHeight = y;
            if (line.type == 0)
                y += 10;
            FontMetrics fm = fms[line.type];
            line.y = y + fm.getAscent();
            y += fm.getHeight();
        }
        linesHeight = y;
    }

    Paint[] paint = paintSteady;
    int yPos = 0;
    int height = getHeight();
    int initY = Math.min(0, initialHeight - height + About.IMAGE_BORDER);
    int maxY = linesHeight - height - initY;
    int totalMillis = 2 * MILLIS_FREEZE + (linesHeight + height) * MILLIS_PER_PIXEL;
    int offs = scroll % totalMillis;
    if (offs >= 0 && offs < MILLIS_FREEZE) {
        // frozen before starting the credits scroll
        int a = 255 * (MILLIS_FREEZE - offs) / MILLIS_FREEZE;
        if (a > 245) {
            paint = null;
        } else if (a < 15) {
            paint = paintSteady;
        } else {
            paint = new Paint[colorBase.length];
            for (int i = 0; i < paint.length; i++) {
                Color hue = colorBase[i];
                paint[i] = new GradientPaint(0.0f, 0.0f, derive(hue, a), 0.0f, fadeStop, hue);
            }
        }
        yPos = initY;
    } else if (offs < MILLIS_FREEZE + maxY * MILLIS_PER_PIXEL) {
        // scrolling through credits
        yPos = initY + (offs - MILLIS_FREEZE) / MILLIS_PER_PIXEL;
    } else if (offs < 2 * MILLIS_FREEZE + maxY * MILLIS_PER_PIXEL) {
        // freezing at bottom of scroll
        yPos = initY + maxY;
    } else if (offs < 2 * MILLIS_FREEZE + (linesHeight - initY) * MILLIS_PER_PIXEL) {
        // scrolling bottom off screen
        yPos = initY + (offs - 2 * MILLIS_FREEZE) / MILLIS_PER_PIXEL;
    } else {
        // scrolling next credits onto screen
        int millis = offs - 2 * MILLIS_FREEZE - (linesHeight - initY) * MILLIS_PER_PIXEL;
        paint = null;
        yPos = -height + millis / MILLIS_PER_PIXEL;
    }

    int width = getWidth();
    int centerX = width / 2;
    maxY = getHeight();
    for (CreditsLine line : lines) {
        int y = line.y - yPos;
        if (y < -100 || y > maxY + 50)
            continue;

        int type = line.type;
        if (paint == null) {
            g.setColor(colorBase[type]);
        } else {
            ((Graphics2D) g).setPaint(paint[type]);
        }
        g.setFont(font[type]);
        int textWidth = fms[type].stringWidth(line.text);
        g.drawString(line.text, centerX - textWidth / 2, line.y - yPos);

        Image img = line.img;
        if (img != null) {
            int x = width - line.imgWidth - About.IMAGE_BORDER;
            int top = y - fms[type].getAscent();
            g.drawImage(img, x, top, this);
        }
    }
}