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:savant.view.swing.Ruler.java

/**
 * Render the background of this graphpane
 * @param g The graphics object to use/*ww w.  j a va2s  . c  om*/
 */
private void renderBackground(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    try {

        Image image = javax.imageio.ImageIO
                .read(getClass().getResource("/savant/images/bar_selected_glossy.png"));
        Composite originalComposite = ((Graphics2D) g).getComposite();
        ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.85F));
        g.drawImage(image, -getWidth(), 0, getWidth() * 3, getHeight(), this);
        ((Graphics2D) g).setComposite(originalComposite);
    } catch (Exception e) {
        LOG.error("Error drawing image background");
    }

    Range r = locationController.getRange();

    // At early points in the GUI initialisation, the range has not yet been set.
    if (r == null) {
        return;
    }

    int[] tickPositions = MiscUtils.getTickPositions(r);
    int separation = tickPositions.length > 1 ? tickPositions[1] - tickPositions[0] : 0;
    int xEnd = Integer.MIN_VALUE;
    FontMetrics fm = g2.getFontMetrics();

    for (int p : tickPositions) {

        int x = MiscUtils.transformPositionToPixel(p, getWidth(), r);
        if (x > xEnd + 10) {
            g2.setColor(new Color(50, 50, 50, 50)); //BrowserDefaults.colorAxisGrid);
            g2.drawLine(x, 0, x, getHeight());

            String numStr = MiscUtils.posToShortStringWithSeparation(p, separation);
            g2.setColor(Color.black);
            g2.drawString(numStr, x + 3, getHeight() / 2 + 3);
            xEnd = x + fm.stringWidth(numStr) + 3;
        }
    }

    if (r.getLength() >= locationController.getRangeStart()) {
        try {
            Image image_left_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_left_bordered.png"));
            int pos = getLeftCapPos();
            g.drawImage(image_left_cap, pos, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, -getWidth(), getHeight());
        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }

    if (r.getLength() >= locationController.getMaxRangeEnd() - locationController.getRangeEnd()) {
        try {
            Image image_right_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_right_bordered.png"));
            int pos = MiscUtils.transformPositionToPixel(locationController.getMaxRangeEnd(), getWidth(),
                    locationController.getRange());
            g.drawImage(image_right_cap, pos - CAP_WIDTH, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, this.getWidth(), this.getHeight());

        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }
}

From source file:jmap2gml.ItemImage.java

@Override
public void draw(Graphics g) {
    Image img = IMAGES.get(itemName);

    int xOffset, yOffset;

    if (config.has(itemName + "XOFFSET")) {
        xOffset = config.getInt(itemName + "XOFFSET");
    } else {/*  w ww  . j  a  va 2 s . co m*/
        xOffset = 0;
    }

    if (config.has(itemName + "YOFFSET")) {
        yOffset = config.getInt(itemName + "YOFFSET");
    } else {
        yOffset = 0;
    }

    if (img != null) {
        int width, height;

        width = (int) (img.getWidth(null) * xScale);
        height = (int) (img.getHeight(null) * yScale);

        g.drawImage(img, x + xOffset, y + yOffset, width, height, null);
    } else {
        super.draw(g);
    }
}

From source file:PictureScaler.java

/**
 * Render all scaled versions 10 times, timing each version and 
 * reporting the results below the appropriate scaled image.
 *//*from ww  w  .  j a  v  a2  s.c om*/
protected void paintComponent(Graphics g) {
    // Scale with NEAREST_NEIGHBOR
    int xLoc = PADDING, yLoc = PADDING;
    long startTime, endTime;
    float totalTime;
    int iterations = 10;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("NEAREST ", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("NEAREST: " + ((endTime - startTime) / 1000000));

    // Scale with BILINEAR
    xLoc += scaleW + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("BILINEAR", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("BILINEAR: " + ((endTime - startTime) / 1000000));

    // Scale with BICUBIC
    xLoc += scaleW + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("BICUBIC", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("BICUBIC: " + ((endTime - startTime) / 1000000));

    // Scale with getScaledInstance
    xLoc += scaleW + PADDING;
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        Image scaledPicture = picture.getScaledInstance(scaleW, scaleH, Image.SCALE_AREA_AVERAGING);
        g.drawImage(scaledPicture, xLoc, yLoc, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("getScaled", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("getScaled: " + ((endTime - startTime) / 1000000));

    // Scale with Progressive Bilinear
    xLoc += scaleW + PADDING;
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        Image scaledPicture = getFasterScaledInstance(picture, scaleW, scaleH,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
        g.drawImage(scaledPicture, xLoc, yLoc, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("Progressive", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("Progressive: " + ((endTime - startTime) / 1000000));
}

From source file:net.sf.firemox.tools.Picture.java

@Override
public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    if (cardImage != null) {
        g.drawImage(cardImage, 0, 0, getWidth(), getHeight(), this);
    }//from ww  w.  j  av  a 2  s  . c  om
}

From source file:view.BackgroundImageController.java

public void setGraphBackgroundImage(final VisualizationViewer vv, final ImageIcon background,
        final double xOffset, final double yOffset) {

    removeBackgroundImage(vv);//w  w w.  j ava 2s  . c o  m

    preRender = new VisualizationViewer.Paintable() {
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            AffineTransform oldXform = g2d.getTransform();
            AffineTransform lat = vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)
                    .getTransform();
            AffineTransform vat = vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)
                    .getTransform();
            AffineTransform at = new AffineTransform();
            at.concatenate(g2d.getTransform());
            at.concatenate(vat);
            at.concatenate(lat);
            g2d.setTransform(at);
            g.drawImage(background.getImage(), (int) Math.round(-background.getIconWidth() / xOffset),
                    (int) Math.round(-background.getIconHeight() / yOffset), background.getIconWidth(),
                    background.getIconHeight(), vv);
            g2d.setTransform(oldXform);
        }

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

    vv.addPreRenderPaintable(preRender);

    background.getImage().flush();
    Runtime.getRuntime().gc();
}

From source file:RasterTest.java

public void updateRenderRaster() {
    // takes the Depth Raster and updates the Render Raster
    // containing the image based on the depth values stored in
    // the Depth Raster.

    // create a temporary BufferedImage for the depth components
    BufferedImage tempBufferedImage = new BufferedImage(m_DepthRaster.getDepthComponent().getWidth(),
            m_DepthRaster.getDepthComponent().getHeight(), BufferedImage.TYPE_INT_RGB);

    // allocate an array of ints to store the depth components from the
    // Depth Raster
    if (m_DepthData == null)
        m_DepthData = new int[m_DepthRaster.getDepthComponent().getWidth()
                * m_DepthRaster.getDepthComponent().getHeight()];

    // copy the depth values from the Raster into the int array
    ((DepthComponentInt) m_DepthRaster.getDepthComponent()).getDepthData(m_DepthData);

    // assign the depth values to the temporary image, the integer depths
    // will be/*  w  w w  .  j a va2 s.c  o m*/
    // interpreted as integer rgb values.
    tempBufferedImage.setRGB(0, 0, m_DepthRaster.getDepthComponent().getWidth(),
            m_DepthRaster.getDepthComponent().getHeight(), m_DepthData, 0,
            m_DepthRaster.getDepthComponent().getWidth());

    // get a graphics device for the image
    Graphics g = tempBufferedImage.getGraphics();
    Dimension size = new Dimension();
    m_RenderRaster.getSize(size);

    // because the Depth Raster is a different size to the Render Raster,
    // i.e. the Depth Raster is canvas width by canvas height and the Render
    // Raster
    // is of aritrary size, we rescale the image here.
    g.drawImage(tempBufferedImage, 0, 0, (int) size.getWidth(), (int) size.getHeight(), null);

    // finally, assign the scaled image to the RenderRaster
    m_RenderRaster.setImage(new ImageComponent2D(BufferedImage.TYPE_INT_RGB, tempBufferedImage));
}

From source file:net.rptools.tokentool.ui.TokenCompositionPanel.java

@Override
protected void paintComponent(Graphics g) {

    Dimension size = getSize();/*  w  ww  .ja v  a2s  . co m*/
    g.setColor(Color.black);
    g.fillRect(0, 0, size.width, size.height);

    int messageY = 15;
    int messageX = 5;

    // BASE
    if (AppState.compositionProperties.isBase()) {
        paintOverlay(g, size);
    }

    // TOKEN
    if (tokenImage != null) {
        int width = (int) (tokenImage.getWidth() * tokenScale);
        int height = (int) (tokenImage.getHeight() * tokenScale);
        g.drawImage(tokenImage, tokenOffsetX, tokenOffsetY, width, height, this);
    } else {
        g.setColor(Color.white);
        g.drawString("Drag an image onto this pane", messageX, messageY);
        messageY += 15;
    }

    if (!AppState.compositionProperties.isBase()) {
        paintOverlay(g, size);
    }
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

private BufferedImage[] getSpecialRAWImage(String name, Color[] palette, int upscalePowerOfTwo)
        throws IllegalAccessException, FileLoadException, IOException {
    RAWFile dat = getRAW(name);//from   www  .ja va2  s. co m
    dat.setPalette(palette);
    BufferedImage[] segs = dat.asSegments(upscalePowerOfTwo);
    for (BufferedImage seg : segs) {
        Graphics g = seg.getGraphics();
        BufferedImage scaled = new BufferedImage(seg.getColorModel(), seg.copyData(null),
                seg.isAlphaPremultiplied(), null);
        g.drawImage(
                scaled.getScaledInstance(seg.getWidth() - 2, seg.getHeight() - 2, Image.SCALE_AREA_AVERAGING),
                1, 1, seg.getWidth() - 2, seg.getHeight() - 2, null);
        g.dispose();
    }
    return segs;
}

From source file:WorldMapGraphDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoom features.// ww w.j av  a2s.  c  o m
 * 
 */
public WorldMapGraphDemo() {
    setLayout(new BorderLayout());

    map.put("TYO", new String[] { "35 40 N", "139 45 E" });
    map.put("PEK", new String[] { "39 55 N", "116 26 E" });
    map.put("MOW", new String[] { "55 45 N", "37 42 E" });
    map.put("JRS", new String[] { "31 47 N", "35 13 E" });
    map.put("CAI", new String[] { "30 03 N", "31 15 E" });
    map.put("CPT", new String[] { "33 55 S", "18 22 E" });
    map.put("PAR", new String[] { "48 52 N", "2 20 E" });
    map.put("LHR", new String[] { "51 30 N", "0 10 W" });
    map.put("HNL", new String[] { "21 18 N", "157 51 W" });
    map.put("NYC", new String[] { "40 77 N", "73 98 W" });
    map.put("SFO", new String[] { "37 62 N", "122 38 W" });
    map.put("AKL", new String[] { "36 55 S", "174 47 E" });
    map.put("BNE", new String[] { "27 28 S", "153 02 E" });
    map.put("HKG", new String[] { "22 15 N", "114 10 E" });
    map.put("KTM", new String[] { "27 42 N", "85 19 E" });
    map.put("IST", new String[] { "41 01 N", "28 58 E" });
    map.put("STO", new String[] { "59 20 N", "18 03 E" });
    map.put("RIO", new String[] { "22 54 S", "43 14 W" });
    map.put("LIM", new String[] { "12 03 S", "77 03 W" });
    map.put("YTO", new String[] { "43 39 N", "79 23 W" });

    cityList = new ArrayList<String>(map.keySet());

    // create a simple graph for the demo
    graph = new DirectedSparseMultigraph<String, Number>();
    createVertices();
    createEdges();

    ImageIcon mapIcon = null;
    String imageLocation = "/images/political_world_map.jpg";
    try {
        mapIcon = new ImageIcon(getClass().getResource(imageLocation));
    } catch (Exception ex) {
        System.err.println("Can't load \"" + imageLocation + "\"");
    }
    final ImageIcon icon = mapIcon;

    Dimension layoutSize = new Dimension(2000, 1000);

    Layout<String, Number> layout = new StaticLayout<String, Number>(graph,
            new ChainedTransformer(new Transformer[] { new CityTransformer(map),
                    new LatLonPixelTransformer(new Dimension(2000, 1000)) }));

    layout.setSize(layoutSize);
    vv = new VisualizationViewer<String, Number>(layout, new Dimension(800, 400));

    if (icon != null) {
        vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {
            public void paint(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                AffineTransform oldXform = g2d.getTransform();
                AffineTransform lat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.LAYOUT).getTransform();
                AffineTransform vat = vv.getRenderContext().getMultiLayerTransformer()
                        .getTransformer(Layer.VIEW).getTransform();
                AffineTransform at = new AffineTransform();
                at.concatenate(g2d.getTransform());
                at.concatenate(vat);
                at.concatenate(lat);
                g2d.setTransform(at);
                g.drawImage(icon.getImage(), 0, 0, icon.getIconWidth(), icon.getIconHeight(), vv);
                g2d.setTransform(oldXform);
            }

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

    vv.getRenderer().setVertexRenderer(new GradientVertexRenderer<String, Number>(Color.white, Color.red,
            Color.white, Color.blue, vv.getPickedVertexState(), false));

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

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    vv.getRenderer().getVertexLabelRenderer().setPositioner(new InsidePositioner());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    add(panel);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    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();

    //        vv.scaleToLayout(scaler);

    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);
    add(controls, BorderLayout.SOUTH);
}

From source file:org.csml.tommo.sugar.modules.QualityHeatMapsPerTileAndBase.java

@Deprecated
private void writeTable2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration) throws IOException {
    final ResultsTableModel model = new ResultsTableModel(this, laneCoordinates, tileNumeration);

    String flowCell = laneCoordinates.getFlowCell();
    Integer lane = laneCoordinates.getLane();

    ZipOutputStream zip = report.zipFile();
    StringBuffer b = report.htmlDocument();
    StringBuffer d = report.dataDocument();

    b.append("<table>\n");
    // Do the headers
    b.append("<tr>\n");
    d.append("#Tiles: ");

    // "row header" for base position number
    b.append("<th></th>\n");
    d.append("\t");
    for (int c = 0; c < model.getColumnCount(); c++) {
        b.append("<th>");
        b.append(model.getColumnName(c));
        d.append(model.getColumnName(c));
        b.append("</th>\n");
        d.append("\t");

        if (c == model.getTopBottomSeparatorColumn()) {
            b.append("<th>");
            b.append("Top-Bottom");
            d.append("Top-Bottom");
            b.append("</th>\n");
            d.append("\t");
        }/*from   ww w.java 2  s.c om*/
    }
    b.append("</tr>\n");
    d.append("\n");

    long before = System.currentTimeMillis();

    // Do the rows
    d.append("#Base Positions: 1-" + maxSequenceLength);
    d.append("\n");
    for (int r = 0; r < model.getRowCount(); r++) {
        b.append("<tr>\n");

        // "header" for base position number
        b.append("<th>");
        int bp = model.getBasePosition(r);
        b.append(model.getCycleID(r) == 0 ? bp : "");
        b.append("</th>\n");

        for (int c = 0; c < model.getColumnCount(); c++) {
            TileBPCoordinates tileBPCoordinate = model.getCoordinateAt(r, c);
            TileCoordinates tileCoordinates = tileBPCoordinate.getTileCoordinate();
            b.append("<td>");
            MeanQualityMatrix matrix = getMeanQualityMatrix(tileBPCoordinate);

            if (matrix != null) {
                String imgFileName = "matrix_" + flowCell + "_" + lane + "_" + tileCoordinates.getTile() + "_"
                        + tileBPCoordinate.getBasePosition() + ".png";
                zip.putNextEntry(new ZipEntry(report.folderName() + "/Images/" + imgFileName));
                BufferedImage image = (BufferedImage) matrix.createBufferedImage(LinearPaintScale.PAINT_SCALE);
                int imgSize = Options.getHeatmapImageSize();
                BufferedImage scaledImage = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
                Graphics g = scaledImage.getGraphics();
                g.drawImage(image, 0, 0, imgSize, imgSize, null);
                g.dispose();
                ImageIO.write(scaledImage, "png", zip);

                b.append("<img src=\"Images/" + imgFileName + "\" alt=\"M[" + tileBPCoordinate.toString()
                        + "]\">\n");
            } else {
                b.append("");
                d.append("Missing matrix for: " + tileBPCoordinate + "\n");
            }
            b.append("</td>\n");

            if (c == model.getTopBottomSeparatorColumn()) {
                b.append("<td></td>\n");
            }
        }
        b.append("</tr>\n");
    }
    long after = System.currentTimeMillis();
    d.append("Creating report time: " + (after - before));

    b.append("</table>\n");
}