Example usage for java.awt Graphics2D drawImage

List of usage examples for java.awt Graphics2D drawImage

Introduction

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

Prototype

public abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

Source Link

Document

Renders a BufferedImage that is filtered with a BufferedImageOp .

Usage

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

/**
 * Create a back cover/*from   w w  w .  j  a va 2s . c  o  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:Main.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

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

    int cx = getSize().width / 2;
    int cy = getSize().height / 2;

    g2.translate(cx, cy);//  w  ww  . j  ava  2  s.c  o m
    g2.rotate(theta * Math.PI / 180);

    Shape oldClip = g2.getClip();
    Shape e = new Ellipse2D.Float(-cx, -cy, cx * 2, cy * 2);
    g2.clip(e);

    Shape c = new Ellipse2D.Float(-cx, -cy, cx * 3 / 4, cy * 2);
    g2.setPaint(new GradientPaint(40, 40, Color.blue, 60, 50, Color.white, true));
    g2.fill(c);

    g2.setPaint(Color.yellow);
    g2.fillOval(cx / 4, 0, cx, cy);

    g2.setClip(oldClip);

    g2.setFont(new Font("Times New Roman", Font.PLAIN, 64));
    g2.setPaint(new GradientPaint(-cx, 0, Color.red, cx, 0, Color.black, false));
    g2.drawString("Hello, 2D!", -cx * 3 / 4, cy / 4);

    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) .75);
    g2.setComposite(ac);

    Shape r = new RoundRectangle2D.Float(0, -cy * 3 / 4, cx * 3 / 4, cy * 3 / 4, 20, 20);
    g2.setStroke(new BasicStroke(4));
    g2.setPaint(Color.magenta);
    g2.fill(r);
    g2.setPaint(Color.green);
    g2.draw(r);

    g2.drawImage(image, -cx / 2, -cy / 2, this);
}

From source file:AnimatedGifEncoder.java

/**
 * Extracts image pixels into byte array "pixels"
 *///from   w  w w .  j  a  v  a2s .  c o m
protected void getImagePixels() {
    int w = image.getWidth();
    int h = image.getHeight();
    int type = image.getType();
    if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR)) {
        // create new image with right size/format
        BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = temp.createGraphics();
        g.drawImage(image, 0, 0, null);
        image = temp;
    }
    pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    try {//w  w  w.j  a v a  2s.c  o  m
        Graphics2D g2d = (Graphics2D) g;
        g2d.clearRect(0, 0, getWidth(), getHeight());
        g2d.drawImage(mBuffer, 0, 0, null);

        if (iCurrentView == ID_MINIMAP) {
            g2d.setColor(Color.YELLOW);

            int mapWidth = rVisiblePart.width;
            int mapHeight = rVisiblePart.height;

            int w = (int) Math.rint(((double) getWidth() / mapWidth) * (double) iWidth);
            int h = (int) Math.rint(((double) getHeight() / mapHeight) * (double) iHeight);

            double posX = ((double) getWidth() / mapWidth * (double) (iX - rVisiblePart.x)) - w / 2;
            double posY = ((double) getHeight() / mapHeight * (double) (iY - rVisiblePart.y)) - h / 2;

            g2d.drawRect((int) Math.rint(posX), (int) Math.rint(posY), w, h);

            if (iCurrentCursor == ImageManager.CURSOR_SHOT) {
                if (rDrag != null) {
                    g2d.setColor(Color.ORANGE);
                    g2d.drawRect((int) rDrag.getMinX(), (int) rDrag.getMinY(),
                            (int) (rDrag.getWidth() - rDrag.getX()), (int) (rDrag.getHeight() - rDrag.getY()));
                }
            } else if (iCurrentCursor == ImageManager.CURSOR_ZOOM) {
                if (rDrag != null) {
                    g2d.setColor(Color.CYAN);
                    g2d.drawRect((int) rDrag.getX(), (int) rDrag.getY(),
                            (int) (rDrag.getWidth() - rDrag.getX()),
                            (int) ((rDrag.getWidth() - rDrag.getX()) * ((double) getHeight()) / getWidth()));
                }
            }
        }

        if (showControls) {
            //g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .2f));
            Rectangle r = minimapButtons.get(ID_MINIMAP);
            g2d.setColor(Color.WHITE);
            Point menuPos = r.getLocation();
            menuPos.translate(-2, -2);
            //draw border
            g2d.fillRect(menuPos.x, menuPos.y, 88, 30);
            g2d.setColor(Color.BLACK);
            //check if mouse is inside minimap button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);
            }
            g2d.drawImage(minimapIcons.get(ID_MINIMAP), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);

            r = minimapButtons.get(ID_ALLY_CHART);
            //check if mouse is inside ally chart button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);
            }
            g2d.drawImage(minimapIcons.get(ID_ALLY_CHART), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);

            r = minimapButtons.get(ID_TRIBE_CHART);
            //check if mouse is inside tribe chart button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);

            }
            g2d.drawImage(minimapIcons.get(ID_TRIBE_CHART), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);
        }
        g2d.dispose();
    } catch (Exception e) {
        logger.error("Failed painting Minimap", e);
    }
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

private void renderBuildings(Graphics2D g2) {
    // Zeichnet die Gebude
    if (buildingList != null) {
        for (int i = 0; i < buildingList.size(); i++) {
            // Alle Gebude durchgehen und zeichnen
            Building tempB = buildingList.get(i);
            // Textur holen
            String tex = tempB.getGraphicsData().getTexture();
            // Grafik aus ImgMap laden
            CoRImage tempImage = imgMap.get(tex);
            // Bild da?
            if (tempImage != null) {
                // Ok, zeichnen
                g2.drawImage(tempImage.getImage(),
                        (tempB.getMainPosition().getX() - tempB.getGraphicsData().offsetX - positionX) * 10,
                        (int) ((tempB.getMainPosition().getY() - tempB.getGraphicsData().offsetY - positionY)
                                * 7.5),// ww w . jav a  2 s  .c  om
                        null);
            } else {
                System.out.println("[RogGraphics][ERROR]: Image \"" + tex + "\" not found!");
            }
        }
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

protected BufferedImage getImage() {
    BufferedImage tempImg = ImageUtils.createCompatibleBufferedImage(mapDim.width, mapDim.height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) tempImg.getGraphics();
    g2d.setColor(new Color(35, 125, 0));
    g2d.fillRect(0, 0, tempImg.getWidth(null), tempImg.getHeight(null));
    g2d.drawImage(mBuffer, 0, 0, null);
    g2d.dispose();//from w  w w  .  j  av  a2 s  .  co  m
    return tempImg;
}

From source file:ucar.unidata.idv.flythrough.ChartDecorator.java

/**
 * _more_//  w  ww . j  av a 2  s.co  m
 *
 * @param g2 _more_
 * @param comp _more_
 *
 * @return _more_
 */
public boolean paintDashboard(Graphics2D g2, JComponent comp) {
    try {
        List<SampleInfo> infos = new ArrayList<SampleInfo>(sampleInfos);
        if (infos.size() == 0) {
            return false;
        }
        Rectangle b = comp.getBounds();
        JFrame dummyFrame = new JFrame("");
        XYSeriesCollection dataset = new XYSeriesCollection();
        JFreeChart chart = Flythrough.createChart(dataset);
        XYPlot xyPlot = (XYPlot) chart.getPlot();

        int chartHeight = b.height - flythrough.getDashboardImage().getHeight(null);
        chartHeight = Math.max(chartHeight, 50);
        int chartWidth = Math.min(chartHeight * 4, b.width);

        int dx = b.width / 2 - chartWidth / 2;
        int dy = 0;

        Image lastImage = lastChartImage;
        if ((lastImage != null) && (lastImage.getWidth(null) == chartWidth)
                && (lastImage.getHeight(null) == chartHeight)) {
            g2.translate(dx, dy);
            g2.drawImage(lastImage, 0, 0, null);
            g2.translate(-dx, -dy);
            return false;
        }

        for (int i = 0; i < infos.size(); i++) {
            SampleInfo info = infos.get(i);
            ValueAxis rangeAxis = new NumberAxis(info.getName());
            if (info.getRange() != null) {
                rangeAxis
                        .setRange(new org.jfree.data.Range(info.getRange().getMin(), info.getRange().getMax()));
            }
            dataset = new XYSeriesCollection();
            dataset.addSeries(info.getSeries());
            xyPlot.setRangeAxis(i, rangeAxis, false);
            xyPlot.setDataset(i, dataset);
            xyPlot.mapDatasetToRangeAxis(i, i);
            final Color color = COLORS[i % COLORS.length];
            XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) {
                public Paint xgetItemPaint(final int row, final int column) {
                    return color;
                }
            };
            renderer.setSeriesPaint(0, color);
            xyPlot.setRenderer(i, renderer);
        }

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(chartWidth, chartHeight));
        dummyFrame.setContentPane(chartPanel);
        dummyFrame.pack();
        Image image = ImageUtils.getImage(chartPanel);
        lastChartImage = image;
        g2.translate(dx, dy);
        g2.drawImage(image, 0, 0, null);
        g2.translate(-dx, -dy);
    } catch (Exception exc) {
        logException("Painting chart", exc);

    }

    return false;

}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

/**
 * Render the pie chart with the given height
 * //w w  w  .ja  va 2 s.  co  m
 * @param height
 *          The height of the resulting image
 * @return The pie chart rendered as an image
 */
public BufferedImage render(int height) {
    BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.scale(zoom, zoom);
    // fill background to white
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(totalWidth, totalHeight));
    // prepare render hints
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // draw shadow image
    g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver());

    double start = 0;
    List<Arc2D> pies = new ArrayList<>();
    // pie segmente erzeugen und fuellen
    if (total == 0) {
        g2.setColor(BRIGHT_GRAY);
        g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
        g2.setColor(Color.WHITE);
        g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
    } else {
        for (Segment s : segments) {
            double portionDegrees = s.getPortion() / total;
            Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor());
            if (withSubSegments) {
                double smallRadius = radius * s.getSubSegmentRatio();
                paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker());
            }
            start += portionDegrees;
            // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen)
            String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0);
            p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25")
            s.setPercent(p + "%");
            pies.add(pie);
        }
        // weissen Rahmen um die pie segmente zeichen
        g2.setColor(Color.WHITE);
        for (Arc2D pie : pies) {
            g2.draw(pie);
        }
    }
    // Legende zeichnen
    renderLegend(g2);
    // "xx%" Label direkt auf die pie segmente zeichen
    g2.setColor(Color.WHITE);
    float fontSize = 32f;
    g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD));
    start = 0;
    for (Segment s : segments) {
        if (s.getPortion() < 1E-6) {
            continue; // ignore segments with portions that are extremely small
        }
        double portionDegrees = s.getPortion() / total;
        double angle = start + portionDegrees / 2; // genau in der Mitte des Segments
        double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char
        int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt);
        int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2);
        g2.drawString(s.getPercent(), x, y);
        start += portionDegrees;
    }
    return image;
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * Creates the UI.//from  w  ww. j  a  va2  s  .  co m
 */
@SuppressWarnings("unchecked")
protected void createUI() {
    currentSize = getCurrentSizeSquare();

    searchText = createTextField(25);
    searchSciNameBtn = createI18NButton("LM_SEARCH");
    list = new JList(listModel);
    imgDisplay = new ImageDisplay(IMG_WIDTH, IMG_HEIGHT, false, true);

    imgDisplay.setChangeListener(this);

    wwPanel = new WorldWindPanel(false);
    wwPanel.setPreferredSize(new Dimension(currentSize, currentSize));
    wwPanel.setZoomInMeters(600000.0);

    imgDisplay.setDoShowText(false);

    searchMyDataBtn = createI18NButton("LM_SRCH_SP_DATA");
    myDataTF = UIHelper.createTextField();

    CellConstraints cc = new CellConstraints();

    PanelBuilder pb1 = new PanelBuilder(new FormLayout("p,2px,f:p:g,2px,p", "p"));
    pb1.add(createI18NFormLabel("LM_SRCH_COL"), cc.xy(1, 1));
    pb1.add(searchText, cc.xy(3, 1));
    pb1.add(searchSciNameBtn, cc.xy(5, 1));

    PanelBuilder myPB = new PanelBuilder(new FormLayout("f:p:g,p", "p,2px,p,2px,p"));
    mySepComp = myPB.addSeparator(getResourceString("LM_MYDATA_TITLE"), cc.xyw(1, 1, 2));
    myPB.add(myDataTF, cc.xyw(1, 3, 2));
    myPB.add(searchMyDataBtn, cc.xy(2, 5));

    PanelBuilder pb2 = new PanelBuilder(new FormLayout("MAX(p;300px),2px,f:p:g", "f:p:g,20px,p"));
    pb2.add(createScrollPane(list), cc.xy(1, 1));
    pb2.add(myPB.getPanel(), cc.xy(1, 3));

    PanelBuilder pb3 = new PanelBuilder(new FormLayout("f:p:g,p,f:p:g", "f:p:g,p,4px,p,f:p:g"));
    pb3.add(createI18NLabel("LM_WRLD_OVRVW", SwingConstants.CENTER), cc.xy(2, 2));
    pb3.add(imgDisplay, cc.xy(2, 4));

    PanelBuilder pb4 = new PanelBuilder(new FormLayout("f:p:g,p,f:p:g", "f:p:g,p,4px,p,f:p:g"));
    pb4.add(createI18NLabel("LM_INTRACT_VW", SwingConstants.CENTER), cc.xy(2, 2));
    pb4.add(wwPanel, cc.xy(2, 4));

    PanelBuilder pb5 = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,p,f:p:g"));
    pb5.add(pb3.getPanel(), cc.xy(1, 1));
    pb5.add(pb4.getPanel(), cc.xy(1, 3));

    PanelBuilder pb = new PanelBuilder(new FormLayout("p,8px,f:p:g", "p,8px,f:p:g"), this);
    pb.add(pb1.getPanel(), cc.xyw(1, 1, 3));
    pb.add(pb2.getPanel(), cc.xy(1, 3));
    pb.add(pb5.getPanel(), cc.xy(3, 3));

    updateMyDataUIState(false);

    searchText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                searchSciNameBtn.doClick();
            }
        }
    });

    myDataTF.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                searchMyDataBtn.doClick();
            }
        }
    });

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (list.getSelectedIndex() == -1) {
                    wwPanel.reset();
                    imgDisplay.setImage(blueMarble);

                } else {
                    SwingWorker<Boolean, Boolean> worker = new SwingWorker<Boolean, Boolean>() {
                        @Override
                        protected Boolean doInBackground() throws Exception {
                            if (doResetWWPanel) {
                                wwPanel.reset();
                            }
                            doSearchOccur();
                            return null;
                        }

                        @Override
                        protected void done() {
                            imgDisplay.repaint();
                        }
                    };
                    worker.execute();
                }
            }
        }
    });

    searchMyDataBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    doSearchSpecifyData(myDataTF.getText().trim());
                }
            });

        }
    });

    searchSciNameBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doSearchGenusSpecies();
        }
    });

    blueMarbleListener = new BufferedImageFetcherIFace() {
        @Override
        public void imageFetched(BufferedImage image) {
            blueMarble = image;
            imgDisplay.setImage(blueMarble);
        }

        @Override
        public void error() {
            blueMarbleTries++;
            if (blueMarbleTries < 5) {
                blueMarbleRetry();
            }
        }
    };

    blueMarbleURL = BG_URL + String.format("WIDTH=%d&HEIGHT=%d", IMG_WIDTH, IMG_HEIGHT);

    pointsMapImageListener = new BufferedImageFetcherIFace() {
        @Override
        public void imageFetched(final BufferedImage image) {
            if (renderImage == null) {
                renderImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_ARGB);
            }
            Graphics2D g2d = renderImage.createGraphics();
            if (g2d != null) {
                g2d.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
                if (blueMarble != null) {
                    g2d.drawImage(blueMarble, 0, 0, null);
                }
                if (image != null) {
                    g2d.drawImage(image, 0, 0, null);
                }
                g2d.dispose();

                imgDisplay.setImage(renderImage);
            }
        }

        @Override
        public void error() {
        }
    };
    blueMarbleRetry();
}

From source file:org.gumtree.vis.awt.CompositePanel.java

@Override
public BufferedImage getImage() {
    BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D gc2 = image.createGraphics();
    gc2.setBackground(Color.white);
    gc2.setPaint(Color.white);//from  w ww.  j  av  a2s  .c  o m
    gc2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
    for (IPlot plot : plotList) {
        if (plot instanceof JPanel) {
            JPanel panel = (JPanel) plot;
            Rectangle2D panelBounds = panel.getBounds();
            Image panelImage = plot.getImage();
            gc2.drawImage(panelImage, (int) panelBounds.getMinX(), (int) panelBounds.getMinY(), panel);
        }
    }
    gc2.dispose();
    return image;
}