Example usage for java.awt.image BufferedImage createGraphics

List of usage examples for java.awt.image BufferedImage createGraphics

Introduction

In this page you can find the example usage for java.awt.image BufferedImage createGraphics.

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:com.fluidops.iwb.deepzoom.ImageLoader.java

private void generateIDCard(URI uri, Map<URI, Set<Value>> facets, String url, File file) {
    int width = 200;
    int height = 200;

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D ig2 = bi.createGraphics();
    ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    ig2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    /* Special ID card handling for certain entity types */

    /*  TODO: special images based on type
    if(facets.containsKey(RDF.TYPE)) {//ww w  .jav a  2 s.c  o  m
    Set<Value> facet = facets.get(RDF.TYPE);
            
    for(Value v : facet)
    {
        if(v.equals(Vocabulary.DCAT_DATASET))
        {
            
            Image img = null;
            try
            {
                img = ImageIO.read( new File( "webapps/ROOT/images/rdf.jpg" ) );
            }
            catch (MalformedURLException e)
            {
                logger.error(e.getMessage(), e);
            }
            catch (IOException e)
            {
                logger.error("Could not get image");
            }
            
            ig2.drawImage( img, 0, 0, null );        
            break;
        }
    }
    } */

    String label = EndpointImpl.api().getDataManager().getLabel(uri);
    Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20);
    ig2.setFont(font);

    FontMetrics fontMetrics = ig2.getFontMetrics();
    int labelwidth = fontMetrics.stringWidth(label);
    if (labelwidth >= width) {
        int fontsize = 20 * width / labelwidth;
        font = new Font(Font.SANS_SERIF, Font.BOLD, fontsize);
        ig2.setFont(font);
        fontMetrics = ig2.getFontMetrics();
    }

    int x = (width - fontMetrics.stringWidth(label)) / 2;
    int y = (fontMetrics.getAscent() + (height - (fontMetrics.getAscent() + fontMetrics.getDescent())) / 2);

    ig2.setPaint(Color.black);

    ig2.drawString(label, x, y);

    BufferedOutputStream out;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        ImageIO.write(bi, "PNG", out);
        out.flush();
        out.close();

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

private void saveImage() {
    LayerViewAwtPanel.logger.debug("record"); //$NON-NLS-1$
    Color bg = this.getBackground();
    BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setColor(bg);/*from  ww  w.j  av a 2s  . c o m*/
    graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
    this.getRenderingManager().copyTo(graphics);
    this.recording = false;
    // this.paintOverlays(graphics);
    graphics.dispose();
    try {
        NumberFormat format = NumberFormat.getInstance();
        format.setMinimumIntegerDigits(3);
        ImgUtil.saveImage(image, this.recordFileName + format.format(this.recordIndex) + ".png"); //$NON-NLS-1$
        this.recordIndex++;
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

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();/*from w  ww . j  av a2 s . c o m*/

    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    ImageIO.write(scaledImage, "jpg", out);
    out.close();

}

From source file:com.schnee.tweetgeister.visualization.TweetgeisterBalloonLayout.java

private void writeGraph() {
    Container c = new Container();

    VisualizationViewer<Node, Integer> vv = new VisualizationViewer<Node, Integer>(balloonLayout,
            new Dimension(3000, 3000));
    vv.setBackground(Color.white);
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
    vv.getRenderContext().setVertexLabelTransformer(new TopicNodeLabeller(graph));
    vv.getRenderContext().setVertexIncludePredicate(new VertexDisplayPredicate(false));
    // add a listener for ToolTips
    vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray));
    //vv.addPreRenderPaintable(rings);
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);
    rings = new Rings(balloonLayout, vv);
    vv.addPreRenderPaintable(rings);/*  w  ww  .  ja  v a  2s  .  c o m*/
    java.awt.image.BufferedImage bi = new java.awt.image.BufferedImage(3000, 3000,
            java.awt.image.BufferedImage.TYPE_INT_RGB);

    Graphics2D gr = bi.createGraphics();

    // MOST-IMPORTANT

    vv.setSize(3000, 3000);

    final ScalingControl scaler = new CrossoverScalingControl();

    vv.scaleToLayout(scaler);

    // MOST-IMPORTANT

    c.addNotify();

    c.add(vv);

    c.setVisible(true);

    c.paintComponents(gr);

    try {
        ImageIO.write(bi, "png", new File("vis.png"));
        System.out.println("done");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:net.rptools.maptool.client.MapTool.java

public static BufferedImage takeMapScreenShot(final PlayerView view) {
    final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer();
    if (renderer == null) {
        return null;
    }/*w  ww.j av  a2  s.  c  o m*/

    Dimension size = renderer.getSize();
    if (size.width == 0 || size.height == 0) {
        return null;
    }

    BufferedImage image = new BufferedImage(size.width, size.height, Transparency.OPAQUE);
    final Graphics2D g = image.createGraphics();
    g.setClip(0, 0, size.width, size.height);

    // Have to do this on the EDT so that there aren't any odd side effects
    // of rendering
    // using a renderer that's on screen
    if (!EventQueue.isDispatchThread()) {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    renderer.renderZone(g, view);
                }
            });
        } catch (InterruptedException ie) {
            MapTool.showError("While creating snapshot", ie);
        } catch (InvocationTargetException ite) {
            MapTool.showError("While creating snapshot", ite);
        }
    } else {
        renderer.renderZone(g, view);
    }

    g.dispose();

    return image;
}

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

private BufferedImage makeOpaque(BufferedImage image) {
    if (image.getType() == BufferedImage.TYPE_CUSTOM) {
        log.warn("makeOpaque {} Unknown Image Type 0: ", getTitle());
        return image;
    }//w  ww.jav a  2 s.co m
    BufferedImage opaqueCopy = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
    Graphics2D g1 = opaqueCopy.createGraphics();
    g1.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getOpacity()));
    g1.drawImage(image, null, 0, 0);
    g1.dispose();
    return opaqueCopy;
}

From source file:edworld.pdfreader4humans.PDFReader.java

public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor,
        boolean showStructure) throws IOException {
    Map<String, Font> fonts = new HashMap<String, Font>();
    PDRectangle cropBox = getPageCropBox(pageNumber);
    BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling),
            Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setBackground(backgroundColor);
    graphics.clearRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(backgroundColor);//from   www .j a va 2 s .co m
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(inkColor);
    graphics.scale(scaling, scaling);
    for (Component component : getFirstLevelComponents(pageNumber))
        draw(component, graphics, inkColor, backgroundColor, showStructure, fonts);
    graphics.dispose();
    return image;
}

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

/**
 * Render the pie chart with the given height
 * //from w w w. ja v  a2  s .  c  o 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:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Creates a thumbnail for the layer as a Resource, and updates the layer with the new thumbnail
 * @param ws The workspace of the layer/* w  w  w.  ja  va  2  s . c o m*/
 * @param layer The layer or layerGroup to get the thumbnail for
 * @return The thumbnail image as a Resource
 * @throws Exception
 */
protected void createThumbnail(WorkspaceInfo ws, PublishedInfo layer, HttpServletRequest baseRequest)
        throws Exception {
    //Sync against this map/layer
    Semaphore s = semaphores.get(layer);
    s.acquire();
    try {
        //(SUITE-1072) Initialize the thumbnail to a blank image in case the WMS request crashes geoserver
        BufferedImage blankImage = new BufferedImage(THUMBNAIL_SIZE * 2, THUMBNAIL_SIZE * 2,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = blankImage.createGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, blankImage.getWidth(), blankImage.getHeight());
        writeThumbnail(layer, blankImage);

        //Set up getMap request
        String url = baseRequest.getScheme() + "://localhost:" + baseRequest.getLocalPort()
                + baseRequest.getContextPath() + "/" + ws.getName() + "/wms/reflect";

        url += "?FORMAT=" + MIME_TYPE;

        ReferencedEnvelope bbox = null;
        if (layer instanceof LayerInfo) {
            url += "&LAYERS=" + layer.getName();
            url += "&STYLES=" + ((LayerInfo) layer).getDefaultStyle().getName();
            bbox = ((LayerInfo) layer).getResource().boundingBox();
        } else if (layer instanceof LayerGroupInfo) {

            LayerGroupHelper helper = new LayerGroupHelper((LayerGroupInfo) layer);
            bbox = ((LayerGroupInfo) layer).getBounds();
            url += "&CRS=" + CRS.toSRS(bbox.getCoordinateReferenceSystem());

            List<LayerInfo> layerList = helper.allLayersForRendering();
            if (layerList.size() > 0) {
                url += "&LAYERS=";
                for (int i = 0; i < layerList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    url += layerList.get(i) == null ? "" : layerList.get(i).getName();
                }
            }
            List<StyleInfo> styleList = helper.allStylesForRendering();
            if (styleList.size() > 0) {
                url += "&STYLES=";
                for (int i = 0; i < styleList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    if (styleList.get(i) == null) {
                        url += layerList.get(i).getDefaultStyle() == null ? ""
                                : layerList.get(i).getDefaultStyle().getName();
                    } else {
                        url += styleList.get(i) == null ? "" : styleList.get(i).getName();
                    }
                }
            }
        } else {
            throw new RuntimeException("layer must be one of LayerInfo or LayerGroupInfo");
        }
        //Set the size of the HR thumbnail
        //Take the smallest bbox dimension as the min dimension. We can then crop the other 
        //dimension to give a square thumbnail
        url += "&BBOX=" + ((float) bbox.getMinX()) + "," + ((float) bbox.getMinY()) + ","
                + ((float) bbox.getMaxX()) + "," + ((float) bbox.getMaxY());
        if (bbox.getWidth() < bbox.getHeight()) {
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE);
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getHeight() / bbox.getWidth()));
        } else {
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE);
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getWidth() / bbox.getHeight()));
        }

        //Run the getMap request through the WMS Reflector
        //WebMap response = wms.reflect(request);            
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedImage image = ImageIO.read(con.getInputStream());
        if (image == null) {
            throw new RuntimeException(
                    "Failed to encode thumbnail for " + ws.getName() + ":" + layer.getName());
        }
        writeThumbnail(layer, image);
    } finally {
        s.release();
    }
}

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

public void saveAsImage(String fileName, int width, int height, boolean doSaveWorldFile, boolean drawOverlay) {
    Color bg = this.getBackground();
    BufferedImage outImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = outImage.createGraphics();
    // TEMP/*from   ww w .  j a va 2s.c  om*/
    graphics.setColor(bg);
    graphics.fillRect(0, 0, width, height);
    int tmpw = this.getWidth();
    int tmph = this.getHeight();
    // We save the old extent to force the Viewport to keep the old
    // window in world coordinates.
    IEnvelope env = this.getViewport().getEnvelopeInModelCoordinates();
    // Artificially resize the canvas to the image dimensions.
    this.setSize(width, height);
    try {
        // We zoom to the old extent in the resized canvas.
        this.getViewport().zoom(env);
    } catch (NoninvertibleTransformException e2) {
        logger.error("In Image Export : failed to zoom in the correct extent.");
        e2.printStackTrace();
    }
    this.renderingManager.renderAll();
    long time = System.currentTimeMillis();
    long twaited = 0;
    while (this.renderingManager.isRendering() && twaited < 15000) {
        // Wait for the rendering to end for a maximum of 15s. If the
        // rendering is not finished after this delay,
        // we give up.
        twaited = System.currentTimeMillis() - time;
    }
    if (this.renderingManager.isRendering()) {
        logger.error("Export to image : waited 15s but the rendering is still not finished. Abort.");
        return;
    }

    // We have to impose a bbox !!!
    this.getRenderingManager().copyTo(graphics);

    if (drawOverlay)
        this.paintOverlays(graphics);
    graphics.dispose();
    try {
        ImgUtil.saveImage(outImage, fileName);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (doSaveWorldFile) {
        String wld = FilenameUtils.removeExtension(fileName) + ".wld";
        try {
            AffineTransform t = this.getViewport().getModelToViewTransform();
            fr.ign.cogit.geoxygene.util.conversion.WorldFileWriter.write(new File(wld), t.getScaleX(),
                    t.getScaleY(), this.getViewport().getViewOrigin().getX(),
                    this.getViewport().getViewOrigin().getY(), this.getHeight());
        } catch (NoninvertibleTransformException e) {
            logger.error("Failed to save the world file associated with the image file " + fileName);
            e.printStackTrace();
        }
    }

    // Finally, rollback the canvas to its original size.
    this.setSize(tmpw, tmph);
    try {
        // Zoom back to the "normal" extent
        this.getViewport().zoom(env);
    } catch (NoninvertibleTransformException e2) {
        logger.error("In Image Export : failed to zoom back to the original LayerViewPanel extent.");
        e2.printStackTrace();
        return;
    }
}