Example usage for java.awt Graphics2D dispose

List of usage examples for java.awt Graphics2D dispose

Introduction

In this page you can find the example usage for java.awt Graphics2D 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:net.shopxx.util.ImageUtil.java

/**
 * ?//w  w  w  .  ja va  2s  .c o  m
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        return;
    }
    if (type == Type.jdk) {
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(watermarkFile.getPath());
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:iqq.util.ImageUtil.java

/**
 * ?/*from ww  w . j  ava2  s .c om*/
 *
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public synchronized static void addWatermark(File srcFile, File destFile, InputStream watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    //watermarkFile == null || !watermarkFile.exists() || 
    if (!srcFile.exists() || watermarkFile == null || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        Log.println("addWatermark null");
        return;
    }
    if (type == Type.jdk) {
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            if (srcBufferedImage == null) {
                return;
            }
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        //operation.addImage(watermarkFile);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.ProfilesComparisonReportChartCanvas.java

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);//from   ww  w. j  a v a 2  s .c om
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);

    // dispose graphic object
    g2d.dispose();

    revalidate();
}

From source file:com.nbt.TileCanvas.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    g2d.setColor(Color.BLACK);/*  w w w .j ava  2  s  .  c o  m*/
    int x = 0, y = 0;
    Dimension size = getSize();
    g2d.fillRect(x, y, size.width, size.height);

    final int altitude = getAltitude();
    for (int w = 0; w < getTileWidth(); w++) {
        x = w * SPRITE_SIZE;
        for (int h = 0; h < getTileHeight(); h++) {
            y = h * SPRITE_SIZE;

            int xOffset = w + getTileX();
            int zOffset = h + getTileZ();
            BufferedImage tile = getBackgroundTile(xOffset, altitude, zOffset);
            if (tile != null)
                g2d.drawImage(tile, x, y, null);
        }
    }

    g2d.dispose();
}

From source file:com.neophob.sematrix.core.generator.Textwriter.java

/**
 * create image./*from  w w w .j  a  v a2  s.c  o m*/
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    //head and tailing space
    maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize;
    int ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY);
    g2 = img.createGraphics();

    g2.setColor(new Color(128));
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);

    g2.drawString(text, internalBufferXSize, ypos);
    DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer();
    byte[] textBuffer = dbi.getData();
    g2.dispose();

    xofs = 0;

    textAsImage = new int[maxXPos * internalBufferYSize];
    for (int i = 0; i < textAsImage.length; i++) {
        if (textBuffer[i] > 10) {
            textAsImage[i] = 127;
        } else {
            textAsImage[i] = 0;
        }
    }

    //clear internalbuffer
    Arrays.fill(this.internalBuffer, 0);
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

/**
 * //from   w w  w  . j  a va 2s  .c o m
 */
public void generate() {
    Rectangle rect = getPanel().getParent().getBounds();
    System.out.println("MAIN[" + rect + "]");
    if (rect.width == 0 || rect.height == 0) {
        return;
    }

    BufferedImage bufImage = new BufferedImage(rect.width, rect.height,
            (doPNG ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB));
    Graphics2D g2 = bufImage.createGraphics();
    if (!doPNG) {
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, rect.width, rect.height);
    }
    g2.setRenderingHints(createTextRenderingHints());
    g2.setFont(tblTracker.getFont());
    getPanel().getParent().paint(g2);

    g2.dispose();

    Component stop = getPanel().getParent();
    Point p = new Point(0, 0);
    calcLoc(p, getPanel().getMainTable(), stop);

    String name = StringUtils.substringAfterLast(getPanel().getMainTable().getClassName(), ".");
    DBTableInfo tblInfo = DBTableIdMgr.getInstance().getByShortClassName(name);
    String fName = schemaDir.getAbsolutePath() + File.separator + name;
    try {
        String origName = fName;
        int i = 1;
        while (pngNameHash.contains(fName)) {
            fName = origName + i;
        }
        pngNameHash.add(fName);

        File html = new File(fName + ".html");
        BufferedWriter output = new BufferedWriter(new FileWriter(html));

        int index = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, index);
        output.write(StringUtils.replace(subContent, "<!-- Title -->", tblInfo.getTitle()));

        File imgFile = new File(fName + (doPNG ? ".png" : ".jpg"));
        output.write("<map name=\"schema\" id=\"schema\">\n");

        Vector<ERDTable> nList = mainPanel.isRoot() ? tblTracker.getTreeAsList(mainPanel.getMainTable())
                : getPanel().getRelTables();
        for (ERDTable erdt : nList) {
            p = new Point(0, 0);
            calcLoc(p, erdt, stop);
            Dimension s = erdt.getSize();
            String linkname = StringUtils.substringAfterLast(erdt.getClassName(), ".");
            output.write("<area shape=\"rect\" coords=\"" + p.x + "," + p.y + "," + (p.x + s.width) + ","
                    + (p.y + s.height) + "\" href=\"" + linkname + ".html\"/>\n");
        }

        output.write("</map>\n");
        output.write("<img border=\"0\" usemap=\"#schema\" src=\"" + imgFile.getName() + "\"/>\n");

        output.write(mapTemplate.substring(index + contentTag.length() + 1, mapTemplate.length()));

        output.close();

        File oFile = new File(schemaDir + File.separator + imgFile.getName());
        System.out.println(oFile.getAbsolutePath());
        if (doPNG) {
            ImageIO.write(bufImage, "PNG", oFile);
        } else {
            writeJPEG(oFile, bufImage, 0.75f);
        }
        //ImageIO.write(bufImage, "JPG", new File(schemaDir + File.separator + imgFile.getName()+".jpg"));

    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchDoItYourselfAttackPlaner.java

@Override
public void resetView() {
    AttackManager.getSingleton().addManagerListener(this);
    //setup renderer and general view
    // ((DoItYourselfAttackTableModel) jAttackTable.getModel()).clear();

    HighlightPredicate.ColumnHighlightPredicate colu = new HighlightPredicate.ColumnHighlightPredicate(0, 1, 2,
            3, 6);//  w  ww  .j  a v  a  2s .c o m
    jAttackTable.setRowHeight(24);
    jAttackTable.getTableHeader().setDefaultRenderer(new DefaultTableHeaderRenderer());
    jAttackTable.setHighlighters(new CompoundHighlighter(colu,
            HighlighterFactory.createAlternateStriping(Constants.DS_ROW_A, Constants.DS_ROW_B)));
    jAttackTable.setColumnControlVisible(true);
    jAttackTable.setDefaultEditor(UnitHolder.class, new UnitCellEditor());
    jAttackTable.setDefaultEditor(Village.class, new VillageCellEditor());
    jAttackTable.setDefaultRenderer(UnitHolder.class, new UnitCellRenderer());
    jAttackTable.setDefaultRenderer(Integer.class,
            new NoteIconCellRenderer(NoteIconCellRenderer.ICON_TYPE.NOTE));
    jAttackTable.setDefaultRenderer(Date.class, new ColoredDateCellRenderer());
    jAttackTable.setDefaultRenderer(Long.class, new ColoredCoutdownCellRenderer());
    jAttackTable.setDefaultEditor(Date.class, new DateSpinEditor());
    jAttackTable.setDefaultEditor(Integer.class, new NoteIconCellEditor(NoteIconCellEditor.ICON_TYPE.NOTE));
    BufferedImage back = ImageUtils.createCompatibleBufferedImage(5, 5, BufferedImage.BITMASK);
    Graphics2D g = back.createGraphics();
    GeneralPath p = new GeneralPath();
    p.moveTo(0, 0);
    p.lineTo(5, 0);
    p.lineTo(5, 5);
    p.closePath();
    g.setColor(Color.GREEN.darker());
    g.fill(p);
    g.dispose();
    jAttackTable.addHighlighter(new PainterHighlighter(HighlightPredicate.EDITABLE,
            new ImagePainter(back, HorizontalAlignment.RIGHT, VerticalAlignment.TOP)));

    DefaultComboBoxModel model = new DefaultComboBoxModel();
    DefaultComboBoxModel model2 = new DefaultComboBoxModel();
    for (UnitHolder unit : DataHolder.getSingleton().getUnits()) {
        model.addElement(unit);
        model2.addElement(unit);
    }
    jUnitBox.setModel(model);
    jUnitComboBox.setModel(model2);
    jUnitBox.setSelectedItem(DataHolder.getSingleton().getUnitByPlainName("ram"));
    jUnitComboBox.setSelectedItem(DataHolder.getSingleton().getUnitByPlainName("ram"));
    jUnitBox.setRenderer(new UnitListCellRenderer());
    jAttackTypeComboBox.setRenderer(new StandardAttackListCellRenderer());

    DefaultComboBoxModel typeModel = new DefaultComboBoxModel();

    for (ManageableType t : StandardAttackManager.getSingleton().getAllElements()) {
        StandardAttack a = (StandardAttack) t;
        typeModel.addElement(a);
    }
    jAttackTypeComboBox.setModel(typeModel);

    jUnitComboBox.setRenderer(new UnitListCellRenderer());

    jSourceVillage.setValue(new Point(500, 500));
    jTargetVillage.setValue(new Point(500, 500));
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            jSourceVillage.updateUI();
            jTargetVillage.updateUI();
        }
    });

}

From source file:net.rptools.maptool.client.ui.ExportDialog.java

/**
 * This is the top-level screen-capture routine. It sends the resulting PNG
 * image to the location previously selected by the user. TODO: It currently
 * calls {@link MapTool#takeMapScreenShot()} for "normal" screenshots, but
 * that's just until this code is considered stable enough.
 * //from w ww .  j ava2 s .com
 * @throws Exception
 */
@SuppressWarnings("unused")
public void screenCapture() throws Exception {
    MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot"));
    ExportRadioButtons type = ExportRadioButtons.getType();
    Player.Role role;
    try {
        switch (type) {
        case TYPE_CURRENT_VIEW:
            // This uses the original screenshot code: I didn't want to touch it, so I need
            // to pass it the same parameter it took before.
            role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER;
            BufferedImage screenCap = MapTool.takeMapScreenShot(renderer.getPlayerView(role));
            // since old screenshot code doesn't throw exceptions, look for null
            if (screenCap == null) {
                throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
            }
            MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));
            ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
            try {
                ImageIO.write(screenCap, "png", imageOut);
                screenCap = null; // Free up the memory as soon as possible
                MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                exportLocation
                        .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray())));
            } finally {
                IOUtils.closeQuietly(imageOut);
            }
            MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
            break;
        case TYPE_ENTIRE_MAP:
            switchToWaitPanel();
            if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")
                    || interactPanel.isSelected("METHOD_IMAGE_WRITER")) {
                // Using a buffer in memory for the whole image
                try {
                    final PlayerView view = preScreenshot();
                    final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));

                    BufferedImage image;
                    if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) {
                        image = new BufferedImage(renderer.getWidth(), renderer.getHeight(),
                                Transparency.OPAQUE);
                        final Graphics2D g = image.createGraphics();
                        //                     g.setClip(0, 0, renderer.getWidth(), renderer.getHeight());
                        renderer.renderZone(g, view);
                        g.dispose();
                    } else {
                        image = new ZoneImageGenerator(renderer, view);
                    }
                    // putContent() can consume quite a bit of time; really should have a progress
                    // meter of some kind here.
                    exportLocation.putContent(pngWriter, image);
                    if (image instanceof ZoneImageGenerator) {
                        log.debug("ZoneImageGenerator() stats: " + image.toString());
                    }
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                } catch (Exception e) {
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
                } finally {
                    postScreenshot();
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
                }
            } else if (interactPanel.isSelected("METHOD_BACKGROUND")) {
                // We must call preScreenshot before creating the ZoneImageGenerator, because
                // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up

                MapTool.showError("This doesn't work! Try one of the other methods.", null);
                if (false) {
                    //
                    // Note: this implementation is the obvious way, which doesn't work, since
                    // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked.
                    //
                    // The suggested implementation by
                    // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html
                    // might work... except that it would have to be part of ZoneRenderer
                    //
                    // The only way to make this really work is to pull the renderZone function
                    // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make
                    // ZoneRenderer create an instance of it, and patch up the code to make it
                    // compatible. Then we can create an instance of ZoneRasterizer, and run it
                    // in a separate thread, since it won't lock in any of the functions that
                    // Swing uses.
                    //
                    class backscreenRender implements Runnable {
                        public void run() {
                            try {
                                PlayerView view = preScreenshot();
                                final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer,
                                        view);
                                final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                                exportLocation.putContent(pngWriter, zoneImageGenerator);
                                // postScreenshot is called by the callback imageComplete()
                            } catch (Exception e) {
                                assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage()
                                        + "'";
                            }
                        }
                    }
                    backscreenRender p = new backscreenRender();
                    new Thread(p).start();
                    repaint();
                }
            } else {
                throw new Exception("Unknown rendering method!");
            }
            break;
        default:
            throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings"));
        }
    } catch (OutOfMemoryError e) {
        MapTool.showError("screenCapture() caught: Out Of Memory", e);
    } catch (Exception ex) {
        MapTool.showError("screenCapture() caught: ", ex);
    }
}

From source file:com.t3.client.ui.ExportDialog.java

/**
 * This is the top-level screen-capture routine. It sends the resulting PNG
 * image to the location previously selected by the user. TODO: It currently
 * calls {@link TabletopTool#takeMapScreenShot()} for "normal" screenshots, but
 * that's just until this code is considered stable enough.
 * //from   w  ww  .ja  v  a 2  s .c om
 * @throws Exception
 */
@SuppressWarnings("unused")
public void screenCapture() throws Exception {
    TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot"));
    ExportRadioButtons type = ExportRadioButtons.getType();
    Player.Role role;
    try {
        switch (type) {
        case TYPE_CURRENT_VIEW:
            // This uses the original screenshot code: I didn't want to touch it, so I need
            // to pass it the same parameter it took before.
            role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER;
            BufferedImage screenCap = TabletopTool.takeMapScreenShot(renderer.getPlayerView(role));
            // since old screenshot code doesn't throw exceptions, look for null
            if (screenCap == null) {
                throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
            }
            TabletopTool.getFrame()
                    .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));
            ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
            try {
                ImageIO.write(screenCap, "png", imageOut);
                screenCap = null; // Free up the memory as soon as possible
                TabletopTool.getFrame()
                        .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                exportLocation
                        .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray())));
            } finally {
                IOUtils.closeQuietly(imageOut);
            }
            TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
            break;
        case TYPE_ENTIRE_MAP:
            switchToWaitPanel();
            if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")
                    || interactPanel.isSelected("METHOD_IMAGE_WRITER")) {
                // Using a buffer in memory for the whole image
                try {
                    final PlayerView view = preScreenshot();
                    final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));

                    BufferedImage image;
                    if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) {
                        image = new BufferedImage(renderer.getWidth(), renderer.getHeight(),
                                Transparency.OPAQUE);
                        final Graphics2D g = image.createGraphics();
                        //                     g.setClip(0, 0, renderer.getWidth(), renderer.getHeight());
                        renderer.renderZone(g, view);
                        g.dispose();
                    } else {
                        image = new ZoneImageGenerator(renderer, view);
                    }
                    // putContent() can consume quite a bit of time; really should have a progress
                    // meter of some kind here.
                    exportLocation.putContent(pngWriter, image);
                    if (image instanceof ZoneImageGenerator) {
                        log.debug("ZoneImageGenerator() stats: " + image.toString());
                    }
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                } catch (Exception e) {
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
                } finally {
                    postScreenshot();
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
                }
            } else if (interactPanel.isSelected("METHOD_BACKGROUND")) {
                // We must call preScreenshot before creating the ZoneImageGenerator, because
                // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up

                TabletopTool.showError("This doesn't work! Try one of the other methods.", null);
                if (false) {
                    //
                    // Note: this implementation is the obvious way, which doesn't work, since
                    // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked.
                    //
                    // The suggested implementation by
                    // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html
                    // might work... except that it would have to be part of ZoneRenderer
                    //
                    // The only way to make this really work is to pull the renderZone function
                    // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make
                    // ZoneRenderer create an instance of it, and patch up the code to make it
                    // compatible. Then we can create an instance of ZoneRasterizer, and run it
                    // in a separate thread, since it won't lock in any of the functions that
                    // Swing uses.
                    //
                    class backscreenRender implements Runnable {
                        @Override
                        public void run() {
                            try {
                                PlayerView view = preScreenshot();
                                final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer,
                                        view);
                                final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                                exportLocation.putContent(pngWriter, zoneImageGenerator);
                                // postScreenshot is called by the callback imageComplete()
                            } catch (Exception e) {
                                assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage()
                                        + "'";
                            }
                        }
                    }
                    backscreenRender p = new backscreenRender();
                    new Thread(p).start();
                    repaint();
                }
            } else {
                throw new Exception("Unknown rendering method!");
            }
            break;
        default:
            throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings"));
        }
    } catch (OutOfMemoryError e) {
        TabletopTool.showError("screenCapture() caught: Out Of Memory", e);
    } catch (Exception ex) {
        TabletopTool.showError("screenCapture() caught: ", ex);
    }
}

From source file:com.t3.client.TabletopTool.java

public static BufferedImage takeMapScreenShot(final PlayerView view) {
    final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer();
    if (renderer == null) {
        return null;
    }/*from w w  w . ja v a  2  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() {
                @Override
                public void run() {
                    renderer.renderZone(g, view);
                }
            });
        } catch (InterruptedException ie) {
            TabletopTool.showError("While creating snapshot", ie);
        } catch (InvocationTargetException ite) {
            TabletopTool.showError("While creating snapshot", ite);
        }
    } else {
        renderer.renderZone(g, view);
    }

    g.dispose();

    return image;
}