Example usage for java.awt Graphics dispose

List of usage examples for java.awt Graphics dispose

Introduction

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

Prototype

public abstract void dispose();

Source Link

Document

Disposes of this graphics context and releases any system resources that it is using.

Usage

From source file:com.openkm.module.direct.DirectWorkflowModule.java

@Override
public byte[] getProcessDefinitionImage(String token, long processDefinitionId, String node)
        throws RepositoryException, DatabaseException, WorkflowException {
    log.debug("getProcessDefinitionImage({}, {}, {})", new Object[] { token, processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;
    Session session = null;//  ww w . j a v  a 2s. co  m

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y
        List<Integer> ordenadas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fix = ordenadas.get(0);

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX(), dNodeInfo.getY() - fix, dNodeInfo.getWidth(), dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();

        // Activity log
        UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_IMAGE", "" + processDefinitionId, null);
    } catch (javax.jcr.RepositoryException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:org.deegree.portal.standard.wms.control.DynLegendListener.java

/**
 * Draws the given symbol to the given image
 * //w  w w .j av  a  2 s  . c  om
 * @param map
 *            Hashmap holding the properties of the legend
 * @param bi
 *            image of the legend
 * @param color
 *            color to fill the graphic
 * @return The drawn BufferedImage
 */
private BufferedImage drawSymbolsToBI(HashMap<String, Object> map, BufferedImage bi, Color color) {

    Graphics g = bi.getGraphics();
    g.setColor(color);
    g.fillRect(0, 0, bi.getWidth(), bi.getHeight());

    String[] layers = (String[]) map.get("NAMES");
    String[] titles = (String[]) map.get("TITLES");
    BufferedImage[] legs = (BufferedImage[]) map.get("IMAGES");
    int h = topMargin;
    for (int i = layers.length - 1; i >= 0; i--) {
        g.drawImage(legs[i], leftMargin, h, null);
        g.setColor(Color.BLACK);
        // just draw title if the flag has been set in listener configuration,
        // the legend image is less than a defined value and a legend image
        // (not missing) has been accessed
        if (useLayerTitle && legs[i].getHeight() < maxNNLegendSize && !missing.contains(layers[i])) {
            g.drawString(titles[i], leftMargin + legs[i].getWidth() + 10,
                    h + (int) (legs[i].getHeight() / 1.2));
        }
        h += legs[i].getHeight() + 5;
        if (separator != null && i > 0) {
            g.drawImage(separator, leftMargin, h, null);
            h += separator.getHeight() + 5;
        }
    }
    g.dispose();
    return bi;
}

From source file:ded.ui.DiagramController.java

/** Write the diagram in PNG format to 'file' with an optional comment.
  * The comment must only use ASCII characters. */
public void writeToPNG(File file, String comment) throws Exception {
    // For a large-ish diagram, this operation takes ~200ms.  For now,
    // I will just acknowledge the delay.  An idea for the future is
    // to add a status bar to the UI, then do the export work in a
    // separate thread, with an indicator in the status bar that will
    // reflect when the operation completes.  I consider it important
    // for the user to know when it finishes so if it takes a long
    // time, they don't in the meantime go copy or view the partially
    // written image.
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {//ww w .  j a v  a 2 s  . com
        // Based on code from:
        // http://stackoverflow.com/questions/5655908/export-jpanel-graphics-to-png-or-gif-or-jpg

        // First, render the image to an in-memory image buffer.
        BufferedImage bi = new BufferedImage(this.getSize().width, this.getSize().height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.createGraphics();
        this.paintWithoutSelectionsShowing(g);
        g.dispose();

        // Now, write that image to a file in PNG format.
        String warning = ImageFileUtil.writeImageToPNGFile(bi, file, comment);
        if (warning != null) {
            SwingUtil.warningMessageBox(this, "File save completed successfully, but while exporting to PNG, "
                    + "there was a warning: " + warning);
        }
    } finally {
        this.setCursor(Cursor.getDefaultCursor());
    }
}

From source file:ded.ui.DiagramController.java

@Override
public void paint(Graphics g) {
    // Swing JPanel is double buffered already, but that is not
    // sufficient to avoid rendering bugs on Apple computers
    // with HiDPI/Retina displays.  This is an attempt at a
    // hack that might circumvent it, effectively triple-buffering
    // the rendering step.
    if (this.tripleBufferMode != 0) {
        // The idea here is if I create an in-memory image with no
        // initial association with the display, whatever hacks Apple
        // has added should not kick in, and I get unscaled pixel
        // rendering.
        BufferedImage bi;/*from  w w w. j a va2 s  .  c  om*/

        if (this.tripleBufferMode == -1) {
            // This is not right because we might be drawing on a
            // different screen than the "default" screen.  Also, I
            // am worried that a "compatible" image might be one
            // subject to the scaling effects I'm trying to avoid.
            GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            bi = gc.createCompatibleImage(this.getWidth(), this.getHeight());
        } else {
            // This is not ideal because the color representation
            // for this hidden image may not match that of the display,
            // necessitating a conversion during 'drawImage'.
            try {
                bi = new BufferedImage(this.getWidth(), this.getHeight(), this.tripleBufferMode);
            } catch (IllegalArgumentException e) {
                // This would happen if 'tripleBufferMode' were invalid.
                if (this.tripleBufferMode == BufferedImage.TYPE_INT_ARGB) {
                    // I don't know how this could happen.  Re-throw.
                    this.log("creating a BufferedImage with TYPE_INT_ARGB failed: "
                            + Util.getExceptionMessage(e));
                    this.log("re-throwing exception...");
                    throw e;
                } else {
                    // Change it to something known to be valid and try again.
                    this.log("creating a BufferedImage with imageType " + this.tripleBufferMode + " failed: "
                            + Util.getExceptionMessage(e));
                    this.log("switching type to TYPE_INT_ARGB and re-trying...");
                    this.tripleBufferMode = BufferedImage.TYPE_INT_ARGB;
                    this.paint(g);
                    return;
                }
            }
        }
        Graphics g2 = bi.createGraphics();
        this.innerPaint(g2);
        g2.dispose();

        g.drawImage(bi, 0, 0, null /*imageObserver*/);
    } else {
        this.innerPaint(g);
    }

    if (this.fpsMeasurementMode) {
        // Immediately trigger another paint cycle.
        this.repaint();
    }
}

From source file:com.jcraft.weirdx.DDXWindowImpSwing.java

public void setSize(int w, int h) {
    boolean resized = false;
    if (w != this.width || h != this.height)
        resized = true;/*from   w  w  w  .  j  av  a 2s.c om*/

    if (!resized && !bwc) {
        return;
    }

    int offx = 0, offy = 0;

    int bitgrabity = window.attr & (15 << 8);
    if (bitgrabity != 0) {
        if (bitgrabity == (7 << 8) || // SouthWest
                bitgrabity == (8 << 8) || // South
                bitgrabity == (9 << 8)) { // SouthEast
            offy = this.height - h;
        }
        if (bitgrabity == (3 << 8) || // NorthEast
                bitgrabity == (6 << 8) || // East
                bitgrabity == (9 << 8)) { // SouthEast
            offx = this.width - w;
        }
    }

    //int originalWidth = this.width, originalHeight = this.height;
    this.width = w;
    this.height = h;
    super.setSize(w + 2 * bw, h + 2 * bw);

    bwc = false;

    if (window.screen.windowmode != WeirdX.InBrowser && window.hasFrame()) {
        java.awt.Window frame = window.getFrame();
        frame.validate();
        Insets insets = frame.getInsets();
        frame.setSize(w + 2 * bw + insets.left + insets.right, h + 2 * bw + insets.top + insets.bottom);
        frame.validate();
    }

    if (window.clss == InputOnly) {
        return;
    }

    if (offi != null && resized) {
        if (w < exposed.x || h < exposed.y) {
            exposed.setBounds(0, 0, 0, 0);
        } else if (w < (exposed.x + exposed.width) || h < (exposed.y + exposed.height)) {
            exposed.setBounds(exposed.x, exposed.y,
                    (exposed.width < (w - exposed.x) ? exposed.width : (w - exposed.x)),
                    (exposed.height < (h - exposed.y) ? exposed.height : (h - exposed.y)));
        }

        try {
            Image tmp = offi;
            Graphics tmpg = offg;

            offi = createImage(w, h);
            offg = offi.getGraphics();
            window.makeBackgroundTile(0, 0, w, h);
            if (bitgrabity != 0) {
                offg.drawImage(tmp, 0, 0, this);
            }

            if (offx != 0 || offy != 0) {
                int copyx = 0, copyy = 0, copyw = w, copyh = h, dx = 0, dy = 0;
                if (offy > 0) {
                    copyy = offy;
                    copyh = h - offy;
                    dy = offy * -1;
                } else if (offy < 0) {
                    dy = offy * -1;
                }
                if (offx > 0) {
                    copyx = offx;
                    copyw = w - offx;
                    dx = offx * -1;
                } else if (offx < 0) {
                    dx = offx * -1;
                }
                offg.copyArea(copyx, copyy, copyw, copyh, dx, dy);
            }

            if (tmp != offi) {
                tmp.flush();
                tmpg.dispose();
            }

            if (bitgrabity == 0) {
                exposed.setBounds(0, 0, 0, 0);
                window.makeBackgroundTile(0, 0, width, height);
            }
            window.currentGC = null;
        } catch (Exception e) {
            LOG.error(e);
            offi = null;
            offg = null;
        } catch (java.lang.OutOfMemoryError e) {
            LOG.error(e);
            offi = null;
            offg = null;
        }
        //System.out.println("DDXW: "+getBackground());
    }
}

From source file:com.jcraft.weirdx.DDXWindowImp.java

public void setSize(int w, int h) {
    boolean resized = false;
    if (w != this.width || h != this.height)
        resized = true;/*from w  ww . jav a 2  s .  c o m*/

    if (!resized && !bwc) {
        return;
    }

    int offx = 0, offy = 0;

    int bitgrabity = window.attr & (15 << 8);
    if (bitgrabity != 0) {
        if (bitgrabity == (7 << 8) || // SouthWest
                bitgrabity == (8 << 8) || // South
                bitgrabity == (9 << 8)) { // SouthEast
            offy = this.height - h;
        }
        if (bitgrabity == (3 << 8) || // NorthEast
                bitgrabity == (6 << 8) || // East
                bitgrabity == (9 << 8)) { // SouthEast
            offx = this.width - w;
        }
    }

    //int originalWidth=this.width, originalHeight = this.height;
    this.width = w;
    this.height = h;
    super.setSize(w + 2 * bw, h + 2 * bw);

    bwc = false;

    if (window.screen.windowmode != WeirdX.InBrowser && window.hasFrame()) {
        java.awt.Window frame = window.getFrame();
        frame.validate();
        Insets insets = frame.getInsets();
        frame.setSize(w + 2 * bw + insets.left + insets.right, h + 2 * bw + insets.top + insets.bottom);
        frame.validate();
    }

    if (window.clss == InputOnly) {
        return;
    }

    if (offi != null && resized) {
        if (w < exposed.x || h < exposed.y) {
            exposed.setBounds(0, 0, 0, 0);
        } else if (w < (exposed.x + exposed.width) || h < (exposed.y + exposed.height)) {
            exposed.setBounds(exposed.x, exposed.y,
                    (exposed.width < (w - exposed.x) ? exposed.width : (w - exposed.x)),
                    (exposed.height < (h - exposed.y) ? exposed.height : (h - exposed.y)));
        }

        try {
            Image tmp = offi;
            Graphics tmpg = offg;

            offi = createImage(w, h);
            offg = offi.getGraphics();
            window.makeBackgroundTile(0, 0, w, h);
            if (bitgrabity != 0) {
                offg.drawImage(tmp, 0, 0, this);
            }

            if (offx != 0 || offy != 0) {
                int copyx = 0, copyy = 0, copyw = w, copyh = h, dx = 0, dy = 0;
                if (offy > 0) {
                    copyy = offy;
                    copyh = h - offy;
                    dy = offy * -1;
                } else if (offy < 0) {
                    dy = offy * -1;
                }
                if (offx > 0) {
                    copyx = offx;
                    copyw = w - offx;
                    dx = offx * -1;
                } else if (offx < 0) {
                    dx = offx * -1;
                }
                offg.copyArea(copyx, copyy, copyw, copyh, dx, dy);
            }

            if (tmp != offi) {
                tmp.flush();
                tmpg.dispose();
            }

            if (bitgrabity == 0) {
                exposed.setBounds(0, 0, 0, 0);
                window.makeBackgroundTile(0, 0, width, height);
            }
            window.currentGC = null;
        } catch (Exception e) {
            LOG.equals(e);
            offi = null;
            offg = null;
        } catch (java.lang.OutOfMemoryError e) {
            LOG.error(e);
            offi = null;
            offg = null;
        }
        //System.out.println("DDXW: "+getBackground());
    }
}

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

/**
 * Update the canvas - draw the latest rendered frame
 * @param warningText//ww  w . java2s  .  com
 */
public synchronized void updateCanvas(String warningText) {
    finalized = false;

    try {
        // flip buffers
        BufferedImage tmp = buffer;
        buffer = backBuffer;
        backBuffer = tmp;

        bufferData = ((DataBufferInt) backBuffer.getRaster().getDataBuffer()).getData();

        Graphics g = buffer.getGraphics();

        if (!warningText.isEmpty()) {
            g.setColor(java.awt.Color.red);
            int x0 = width / 2;
            int y0 = height / 2;
            g.setFont(infoFont);
            if (fontMetrics == null) {
                fontMetrics = g.getFontMetrics();
            }
            g.drawString(warningText, x0 - fontMetrics.stringWidth(warningText) / 2, y0);
        } else {

            if (renderState == RenderState.PREVIEW) {
                int x0 = width / 2;
                int y0 = height / 2;
                g.setColor(java.awt.Color.white);
                g.drawLine(x0, y0 - 4, x0, y0 + 4);
                g.drawLine(x0 - 4, y0, x0 + 4, y0);
                g.setFont(infoFont);
                Ray ray = new Ray();
                if (trace(ray) && ray.getCurrentMaterial() instanceof Block) {
                    Block block = (Block) ray.getCurrentMaterial();
                    g.drawString(String.format("target: %.2f m", ray.distance), 5, height - 18);
                    g.drawString(String.format("[0x%08X] %s (%s)", ray.getCurrentData(), block,
                            block.description(ray.getBlockData())), 5, height - 5);
                }
                Vector3d pos = camera.getPosition();
                g.drawString(String.format("(%.1f, %.1f, %.1f)", pos.x, pos.y, pos.z), 5, 11);
            }
        }

        g.dispose();
    } catch (IllegalStateException e) {
        Log.error("Unexpected exception while rendering back buffer", e);
    }
}

From source file:ded.ui.DiagramController.java

/** Check to see if the font is rendering properly.  I have had a
  * lot of trouble getting this to work on a wide range of
  * machines and JVMs.  If the font rendering does not work, just
  * alert the user to the problem but keep going. */
public void checkFontRendering() {
    // Render the glyph for 'A' in a box just large enough to
    // contain it when rendered properly.
    int width = 9;
    int height = 11;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    ColorModel colorModel = bi.getColorModel();

    g.setColor(Color.WHITE);// w  ww  . j  a  v a 2  s  .co  m
    g.fillRect(0, 0, width, height);

    g.setColor(Color.BLACK);
    g.setFont(this.dedWindow.diagramFont);
    g.drawString("A", 0, 10);

    // Print that glyph as a string.
    StringBuilder sb = new StringBuilder();
    for (int y = 0; y < height; y++) {
        int bits = 0;
        for (int x = 0; x < width; x++) {
            int pixel = bi.getRGB(x, y);
            int red = colorModel.getRed(pixel);
            int green = colorModel.getGreen(pixel);
            int blue = colorModel.getBlue(pixel);
            int alpha = colorModel.getAlpha(pixel);
            boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255);
            boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255);
            sb.append(
                    isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")"));

            bits <<= 1;
            if (!isWhite) {
                bits |= 1;
            }
        }
        sb.append(String.format("  (0x%03X)\n", bits));
    }

    // Also include some of the font metrics.
    FontMetrics fm = g.getFontMetrics();
    sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')="
            + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n");

    String actualGlyph = sb.toString();

    g.dispose();

    // The expected glyph and metrics.
    String expectedGlyph = "_________  (0x000)\n" + "____X____  (0x010)\n" + "___X_X___  (0x028)\n"
            + "___X_X___  (0x028)\n" + "__X___X__  (0x044)\n" + "__X___X__  (0x044)\n" + "__XXXXX__  (0x07C)\n"
            + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_________  (0x000)\n"
            + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n";

    if (!expectedGlyph.equals(actualGlyph)) {
        // Currently, this is known to happen when using OpenJDK 6
        // and 7, with 6 being close to right and 7 being very bad.
        // I also have reports of it happening on certain Mac OS/X
        // systems, but I haven't been able to determine what the
        // important factor there is.
        String warningMessage = "There is a problem with the font rendering.  The glyph "
                + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n"
                + actualGlyph + "\n" + "This probably means there is a bug in the TrueType "
                + "font library.  You might try a different Java version.  "
                + "(I'm working on how to solve this permanently.)";
        System.err.println(warningMessage);
        this.log(warningMessage);
        SwingUtil.errorMessageBox(null /*component*/, warningMessage);
    }
}

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

/**
 * Generate an image replicating the users map in the browser.
 * //from w w w .j av a 2s  .com
 * @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:net.geoprism.dashboard.DashboardMap.java

/**
 * Builds a combined image layer of all the layers in a saved map.
 * /*from  w w w  .j  av  a 2s .  com*/
 * @mapWidth
 * @mapHeight
 * @orderedLayers
 * @mapBounds - expects json object {"bottom":"VALUE", "top":"VALUE", "left":"VALUE", "right":"VALUE"}
 */
public BufferedImage getLayersExportCanvas(int mapWidth, int mapHeight, DashboardLayer[] orderedLayers,
        String mapBounds) {
    String bottom;
    String top;
    String right;
    String left;
    String processingFormat = "png"; // needed to allow transparency on each overlay before combining to a single
                                     // map/format
    Graphics mapBaseGraphic = null;
    BufferedImage base = null;

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

        // Get bounds of the map
        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);
        }

        // Generates map overlays and combines them into a single map image
        for (DashboardLayer layer : orderedLayers) {
            // if (layer instanceof DashboardThematicLayer)
            // {
            Graphics2D newOverlayBaseGraphic = null;
            Graphics2D mapLayerGraphic2d = null;

            String layersString = GeoserverProperties.getWorkspace() + ":" + layer.getViewName();

            StringBuffer requestURL = new StringBuffer();
            requestURL.append(GeoserverProperties.getLocalPath() + "/wms?");
            requestURL.append("LAYERS=" + layersString);
            requestURL.append("&");
            requestURL.append("STYLES="); // there are no geoserver styles being added. sld's are used instead
            requestURL.append("&");
            requestURL.append("SRS=EPSG%3A4326");
            requestURL.append("&");
            requestURL.append("TRANSPARENT=true");
            requestURL.append("&");
            requestURL.append("ISBASELAYER=false"); // in the browser the baselayer prop is set for the 1st layer in the
                                                    // map.
            requestURL.append("&");
            requestURL.append(
                    "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&EXCEPTIONS=application%2Fvnd.ogc.se_inimage");
            requestURL.append("&");
            requestURL.append("FORMAT=image%2F" + processingFormat);
            requestURL.append("&");
            requestURL.append("BBOX=" + left + "," + bottom + "," + right + "," + top);
            requestURL.append("&");
            requestURL.append("WIDTH=" + Integer.toString(mapWidth));
            requestURL.append("&");
            requestURL.append("HEIGHT=" + Integer.toString(mapHeight));

            try {
                BufferedImage layerImg = this.getImageFromGeoserver(requestURL.toString());
                BufferedImage newOverlayBase = new BufferedImage(mapWidth, mapHeight,
                        BufferedImage.TYPE_INT_ARGB);

                newOverlayBaseGraphic = newOverlayBase.createGraphics();

                // Add transparency to the layerGraphic
                // This is set in JavaScript in the app so we are replicating browser side transparency settings that are
                // applied to the whole layer
                AlphaComposite thisLayerComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                        this.getLayerOpacity(layer));
                mapLayerGraphic2d = layerImg.createGraphics();
                newOverlayBaseGraphic.setComposite(thisLayerComposite);

                // Add the current layerGraphic to the base image
                newOverlayBaseGraphic.drawImage(layerImg, 0, 0, null);
                mapBaseGraphic.drawImage(newOverlayBase, 0, 0, null);

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

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

    return base;
}