Example usage for java.awt.image BufferedImage getGraphics

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

Introduction

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

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:org.mwc.cmap.xyplot.views.XYPlotView.java

protected void bitmapToClipBoard(JComponent component) {
    Point size = _plotControl.getSize();
    final BufferedImage img = new BufferedImage(size.x, size.y, BufferedImage.TYPE_INT_ARGB);
    Graphics g = img.getGraphics();
    g.setColor(component.getForeground());
    g.setFont(component.getFont());/*from w w w.  j  a  v a  2s  .c  o  m*/
    component.setSize(size.x, size.y);
    component.paint(g);
    Transferable t = new Transferable() {

        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[] { DataFlavor.imageFlavor };
        }

        public boolean isDataFlavorSupported(DataFlavor flavor) {
            if (flavor == DataFlavor.imageFlavor)
                return true;
            return false;
        }

        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (isDataFlavorSupported(flavor)) {
                return img;
            }
            return null;
        }

    };

    ClipboardOwner co = new ClipboardOwner() {

        public void lostOwnership(java.awt.datatransfer.Clipboard clipboard, Transferable contents) {
        }

    };
    java.awt.datatransfer.Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    cb.setContents(t, co);

}

From source file:com.ricemap.spateDB.operations.Plot.java

/**
 * Combines images of different datasets into one image that is displayed
 * to users.//from   w ww.  j a  v  a  2  s  . c om
 * @param fs The file system that contains the datasets and images
 * @param files Paths to directories which contains the datasets
 * @param includeBoundaries Also plot the indexing boundaries of datasets
 * @return An image that is the combination of all datasets images
 * @throws IOException
 */
public static BufferedImage combineImages(Configuration conf, Path[] files, boolean includeBoundaries,
        int width, int height) throws IOException {
    BufferedImage result = null;
    // Retrieve the MBRs of all datasets
    Prism allMbr = new Prism(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
            -Double.MAX_VALUE, -Double.MAX_VALUE);
    for (Path file : files) {
        FileSystem fs = file.getFileSystem(conf);
        Prism mbr = FileMBR.fileMBR(fs, file, null);
        allMbr.expand(mbr);
    }

    // Adjust width and height to maintain aspect ratio
    if ((allMbr.x2 - allMbr.x1) / (allMbr.y2 - allMbr.y1) > (double) width / height) {
        // Fix width and change height
        height = (int) ((allMbr.y2 - allMbr.y1) * width / (allMbr.x2 - allMbr.x1));
    } else {
        width = (int) ((allMbr.x2 - allMbr.x1) * height / (allMbr.y2 - allMbr.y1));
    }
    result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    for (Path file : files) {
        FileSystem fs = file.getFileSystem(conf);
        if (fs.getFileStatus(file).isDir()) {
            // Retrieve the MBR of this dataset
            Prism mbr = FileMBR.fileMBR(fs, file, null);
            // Compute the coordinates of this image in the whole picture
            mbr.x1 = (mbr.x1 - allMbr.x1) * width / allMbr.getWidth();
            mbr.x2 = (mbr.x2 - allMbr.x1) * width / allMbr.getWidth();
            mbr.y1 = (mbr.y1 - allMbr.y1) * height / allMbr.getHeight();
            mbr.y2 = (mbr.y2 - allMbr.y1) * height / allMbr.getHeight();
            // Retrieve the image of this dataset
            Path imagePath = new Path(file, "_data.png");
            if (!fs.exists(imagePath))
                throw new RuntimeException("Image " + imagePath + " not ready");
            FSDataInputStream imageFile = fs.open(imagePath);
            BufferedImage image = ImageIO.read(imageFile);
            imageFile.close();
            // Draw the image
            Graphics graphics = result.getGraphics();
            graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(), (int) mbr.getHeight(),
                    null);
            graphics.dispose();

            if (includeBoundaries) {
                // Plot also the image of the boundaries
                // Retrieve the image of the dataset boundaries
                imagePath = new Path(file, "_partitions.png");
                if (fs.exists(imagePath)) {
                    imageFile = fs.open(imagePath);
                    image = ImageIO.read(imageFile);
                    imageFile.close();
                    // Draw the image
                    graphics = result.getGraphics();
                    graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(),
                            (int) mbr.getHeight(), null);
                    graphics.dispose();
                }
            }
        }
    }

    return result;
}

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/*from w  w  w.j av a2 s.  c om*/
    // 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:edu.umn.cs.spatialHadoop.operations.Plot.java

/**
 * Combines images of different datasets into one image that is displayed
 * to users.// w  w  w.  j  a  v a2 s.  c om
 * @param fs The file system that contains the datasets and images
 * @param files Paths to directories which contains the datasets
 * @param includeBoundaries Also plot the indexing boundaries of datasets
 * @return An image that is the combination of all datasets images
 * @throws IOException
 */
public static BufferedImage combineImages(Configuration conf, Path[] files, boolean includeBoundaries,
        int width, int height) throws IOException {
    BufferedImage result = null;
    // Retrieve the MBRs of all datasets
    Rectangle allMbr = new Rectangle(Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
    for (Path file : files) {
        FileSystem fs = file.getFileSystem(conf);
        Rectangle mbr = FileMBR.fileMBR(fs, file, null);
        allMbr.expand(mbr);
    }

    // Adjust width and height to maintain aspect ratio
    if ((allMbr.x2 - allMbr.x1) / (allMbr.y2 - allMbr.y1) > (double) width / height) {
        // Fix width and change height
        height = (int) ((allMbr.y2 - allMbr.y1) * width / (allMbr.x2 - allMbr.x1));
    } else {
        width = (int) ((allMbr.x2 - allMbr.x1) * height / (allMbr.y2 - allMbr.y1));
    }
    result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    for (Path file : files) {
        FileSystem fs = file.getFileSystem(conf);
        if (fs.getFileStatus(file).isDir()) {
            // Retrieve the MBR of this dataset
            Rectangle mbr = FileMBR.fileMBR(fs, file, null);
            // Compute the coordinates of this image in the whole picture
            mbr.x1 = (mbr.x1 - allMbr.x1) * width / allMbr.getWidth();
            mbr.x2 = (mbr.x2 - allMbr.x1) * width / allMbr.getWidth();
            mbr.y1 = (mbr.y1 - allMbr.y1) * height / allMbr.getHeight();
            mbr.y2 = (mbr.y2 - allMbr.y1) * height / allMbr.getHeight();
            // Retrieve the image of this dataset
            Path imagePath = new Path(file, "_data.png");
            if (!fs.exists(imagePath))
                throw new RuntimeException("Image " + imagePath + " not ready");
            FSDataInputStream imageFile = fs.open(imagePath);
            BufferedImage image = ImageIO.read(imageFile);
            imageFile.close();
            // Draw the image
            Graphics graphics = result.getGraphics();
            graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(), (int) mbr.getHeight(),
                    null);
            graphics.dispose();

            if (includeBoundaries) {
                // Plot also the image of the boundaries
                // Retrieve the image of the dataset boundaries
                imagePath = new Path(file, "_partitions.png");
                if (fs.exists(imagePath)) {
                    imageFile = fs.open(imagePath);
                    image = ImageIO.read(imageFile);
                    imageFile.close();
                    // Draw the image
                    graphics = result.getGraphics();
                    graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(),
                            (int) mbr.getHeight(), null);
                    graphics.dispose();
                }
            }
        }
    }

    return result;
}

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 a va2s .c  o  m
 * @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;
}

From source file:org.openmicroscopy.shoola.agents.measurement.view.IntensityView.java

/** Save the results to an Excel File. */
private void saveResults() {
    channelsSelectionForm = new ChannelSelectionForm(channelName);
    FileChooser chooser = view.createSaveToExcelChooser();
    chooser.addComponentToControls(channelsSelectionForm);

    if (chooser.showDialog() != JFileChooser.APPROVE_OPTION)
        return;//  w  w  w .j  av a 2s .  c  om
    File file = chooser.getFormattedSelectedFile();

    List<Integer> channels = channelsSelectionForm.getUserSelection();
    if (channels == null || channels.size() == 0) {
        UserNotifier un = MeasurementAgent.getRegistry().getUserNotifier();
        un.notifyInfo("Save Results", " Please select at least a channel.");
        view.setStatus("No Channel selected to output.");

        return;
    }
    ExcelWriter writer = null;
    try {
        writer = new ExcelWriter(file.getAbsolutePath());
        writer.openFile();
        writer.createSheet("Channel Summary");
        Iterator<Coord3D> coordMapIterator = shapeMap.keySet().iterator();
        Coord3D currentCoord;
        int n = channels.size();
        Integer channel;
        if (channelSummarySelected(channels))
            outputSummary(writer, shapeMap);
        BufferedImage originalImage = model.getRenderedImage();
        if (originalImage != null) {
            BufferedImage image = Factory.copyBufferedImage(originalImage);

            // Add the ROI for the current plane to the image.
            //TODO: Need to check that.
            model.setAttributes(MeasurementAttributes.SHOWID, true);
            model.getDrawingView().print(image.getGraphics());
            model.setAttributes(MeasurementAttributes.SHOWID, false);
            try {
                writer.addImageToWorkbook("ThumbnailImage", image);
            } catch (Exception e) {
                Logger logger = MeasurementAgent.getRegistry().getLogger();
                logger.error(this, "Cannot write Image: " + e.toString());
            }
            int col = writer.getMaxColumn(0);
            writer.writeImage(0, col + 1, 256, 256, "ThumbnailImage");
        }
        String name;
        String sheet;
        if (channelSummarySelected(channels) && channels.size() != 1)
            while (coordMapIterator.hasNext()) {
                currentCoord = coordMapIterator.next();
                for (int i = 0; i < n; i++) {
                    channel = channels.get(i);
                    if (channel == ChannelSelectionForm.SUMMARYVALUE)
                        continue;
                    if (!nameMap.containsKey(channelName.get(channel)))
                        continue;
                    int rowIndex = 0;
                    name = channelName.get(channel);
                    sheet = CHANNEL_SHEET + name;
                    //First check if the sheet already exists.
                    if (writer.setCurrentSheet(sheet) == null)
                        writer.createSheet(sheet);
                    writeHeader(writer, rowIndex, currentCoord);
                    channel = nameMap.get(name);
                    writeData(writer, rowIndex, currentCoord, channel.intValue());
                }
            }
        writer.close();
    } catch (Exception e) {
        Logger logger = MeasurementAgent.getRegistry().getLogger();
        logger.error(this, "Cannot save ROI results: " + e.toString());

        UserNotifier un = MeasurementAgent.getRegistry().getUserNotifier();
        String message = "An error occurred while trying to" + " save the data.\nPlease try again.";
        if (e instanceof NumberFormatException) {
            message = "We only support the British/American style of "
                    + "representing numbers,\nusing a decimal point rather " + "than a comma.";
        }
        un.notifyInfo("Save Results", message);
        //delete the file
        file.delete();
        try {
            writer.close();
        } catch (Exception e2) {
            //ignore: cannot close the writer.
        }

        return;
    }

    Registry reg = MeasurementAgent.getRegistry();
    UserNotifier un = reg.getUserNotifier();
    un.notifyInfo("Save ROI results", "The ROI results have been " + "successfully saved.");
}

From source file:edu.ku.brc.af.ui.db.TextFieldWithQuery.java

/**
 * Process the results from the search//from w  w  w .j  a va  2s  .  c om
 * @param customQuery the query
 * @param advanceFocus
 */
private void processResults(final CustomQueryIFace customQuery, int advanceFocus) {
    searchedForText = prevEnteredText;

    List<?> dataObjList = customQuery.getDataObjects();
    if (dataObjList == null || dataObjList.size() == 0) {
        if (doAddAddItem) {
            showPopup(advanceFocus);
        }

    } else {
        Dimension dim = getSize();
        if (fontMetrics == null) {
            Font font = getFont();
            BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
            fontMetrics = bi.getGraphics().getFontMetrics(font);
        }

        boolean isFirst = true;
        duplicatehash.clear();
        for (Object obj : dataObjList) {
            Object[] array = (Object[]) obj;

            if (isFirst) {
                numColumns = array.length - 1;
                values = new Object[numColumns];
                isFirst = false;
            }

            Integer id = (Integer) array[numColumns];
            idList.addElement(id);

            if (duplicatehash.get(id) == null) {
                duplicatehash.put(id, array);

                if (numColumns == 1) {
                    Object value = array[0].toString();
                    if (uiFieldFormatter != null) {
                        value = uiFieldFormatter.formatToUI(value);

                    } else if (StringUtils.isNotEmpty(format)) {
                        Object oldVal = builder == null ? null : value;
                        value = UIHelper.getFormattedValue(format, value);
                        if (builder != null && value == null && oldVal != null) {
                            //customized qbx format interfering with builder's selected field(s).
                            value = oldVal;
                        }
                    }
                    list.addElement(value != null ? value.toString() : "xxx");

                } else {
                    try {
                        for (int i = 0; i < numColumns; i++) {
                            Object val = array[i];
                            if (val instanceof Calendar) {
                                val = scrDateFormat.format((Calendar) val);
                            } else if (val instanceof Date) {
                                val = scrDateFormat.format((Date) val);
                            }
                            if (val instanceof FormDataObjIFace) {
                                val = ((FormDataObjIFace) val).getIdentityTitle();
                            }
                            values[i] = val != null ? val : null; //$NON-NLS-1$
                        }

                        String valStr = (String) UIHelper.getFormattedValue(format, values);

                        if (returnCount <= popupDlgThreshold && fontMetrics.stringWidth(valStr) > dim.width) {
                            int len = valStr.length() - 5;
                            while (len > 25) {
                                valStr = valStr.substring(0, len);
                                if (fontMetrics.stringWidth(valStr) < dim.width) {
                                    valStr = valStr + "...";
                                    break;
                                }
                                len -= 5;
                            }
                        }

                        // Minor hack for Bug 5824 for names with no first name
                        // In the future we may want to do a strip of spaces form the end first
                        if (valStr.endsWith(", ")) {
                            valStr = valStr.substring(0, valStr.length() - 2);
                        }
                        list.addElement(valStr);

                    } catch (java.util.IllegalFormatConversionException ex) {
                        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TextFieldWithQuery.class,
                                ex);
                        ex.printStackTrace();

                        list.addElement(values[0] != null ? values[0].toString() : "(No Value)"); //$NON-NLS-1$
                    }

                }
            }
        }

        if (idList.size() > 0 && returnCount != null) {
            if (tabOutSearch && idList.size() == 1) {
                selectedId = idList.elementAt(0);
                setText(list.get(0));
                notifyListenersOfChange(textField);

            } else if (returnCount > popupDlgThreshold) {
                showDialog(advanceFocus);

            } else {
                showPopup(advanceFocus);
            }

        } else {
            setText(""); //$NON-NLS-1$
        }

        duplicatehash.clear();
    }
}

From source file:org.openmicroscopy.shoola.agents.imviewer.util.saver.ImgSaver.java

/** 
 * Saves the displayed images. //www .j  a  va  2  s  .  c  om
 * 
 * @param init   Pass <code>true</code> to initialize the images to save,
 *             <code>false</code> otherwise.
 */
void saveImage(boolean init) {
    if (ImViewerAgent.hasOpenGLSupport()) {
        saveAsTexture();
        return;
    }

    UserNotifier un = ImViewerAgent.getRegistry().getUserNotifier();
    if (init)
        createImages(uiDelegate.getSavingType());
    //Builds the image to display.
    boolean unitBar = model.isUnitBar();
    String v = getUnitBarValue();
    int s = (int) getUnitBarSize();
    boolean constrain;
    try {
        String name = uiDelegate.getSelectedFilePath();

        // make sure the parent directory paths all exist
        FileUtils.forceMkdir(new File(name).getParentFile());

        if (imageComponents == null) {
            constrain = unitBar && v != null && s < mainImage.getWidth() && imageType == ImgSaverUI.IMAGE;
            writeSingleImage(mainImage, constrain, name);
        } else {
            if (mainImage == null)
                return;
            Iterator i;
            int h, w;
            BufferedImage newImage;
            Graphics2D g2;
            if (uiDelegate.isSaveImagesInSeparatedFiles()) {
                constrain = unitBar && v != null && s < mainImage.getWidth() && imageType == ImgSaverUI.IMAGE;
                writeSingleImage(mainImage, constrain, name);
                i = imageComponents.iterator();
                int j = 0;
                while (i.hasNext()) {
                    constrain = unitBar && v != null && imageType != ImgSaverUI.LENS_IMAGE_AND_COMPONENTS;
                    writeSingleImage((BufferedImage) i.next(), constrain, name + "_" + j);
                    j++;
                }
            } else {
                int width = mainImage.getWidth();
                h = mainImage.getHeight();
                int n = imageComponents.size();
                w = width * (n + 1) + ImgSaverPreviewer.SPACE * (n - 1);

                newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                g2 = (Graphics2D) newImage.getGraphics();
                g2.setColor(Color.WHITE);
                ImagePaintingFactory.setGraphicRenderingSettings(g2);
                //Paint the original image.
                i = imageComponents.iterator();
                int x = 0;
                while (i.hasNext()) {
                    g2.drawImage((BufferedImage) i.next(), null, x, 0);
                    if (unitBar && v != null && imageType != ImgSaverUI.LENS_IMAGE_AND_COMPONENTS)
                        ImagePaintingFactory.paintScaleBar(g2, x + width - s - 10, h - 10, s, v);
                    x += width;
                    g2.fillRect(x, 0, ImgSaverPreviewer.SPACE, h);
                    x += ImgSaverPreviewer.SPACE;
                }
                g2.drawImage(mainImage, null, x, 0);
                if (unitBar && v != null && !(imageType == ImgSaverUI.LENS_IMAGE_AND_COMPONENTS
                        || imageType == ImgSaverUI.LENS_IMAGE))
                    ImagePaintingFactory.paintScaleBar(g2, x + width - s - 10, h - 10, s, v);
                writeImage(newImage, name);
            }
        }
    } catch (Exception e) {
        un.notifyInfo("Saving Image", "An error occurred while saving " + "the image.");
        return;
    }
    notifySave(getExtendedName(uiDelegate.getSelectedFilePath(), format));
    if (uiDelegate.isSetDefaultFolder())
        UIUtilities.setDefaultFolder(uiDelegate.getCurrentDirectory());
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

/**
 * @see Graphics#drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver)
 *//*  ww w  .  ja  v  a  2s .  c om*/
@Override
public boolean drawImage(final Image img, final int dx1, final int dy1, final int dx2, final int dy2,
        final int sx1, final int sy1, final int sx2, final int sy2, final Color bgcolor,
        final ImageObserver observer) {
    waitForImage(img);
    final double dwidth = (double) dx2 - dx1;
    final double dheight = (double) dy2 - dy1;
    final double swidth = (double) sx2 - sx1;
    final double sheight = (double) sy2 - sy1;

    // if either width or height is 0, then there is nothing to draw
    if (dwidth == 0 || dheight == 0 || swidth == 0 || sheight == 0) {
        return true;
    }

    final double scalex = dwidth / swidth;
    final double scaley = dheight / sheight;

    final double transx = sx1 * scalex;
    final double transy = sy1 * scaley;
    final AffineTransform tx = AffineTransform.getTranslateInstance(dx1 - transx, dy1 - transy);
    tx.scale(scalex, scaley);

    final BufferedImage mask = new BufferedImage(img.getWidth(observer), img.getHeight(observer),
            BufferedImage.TYPE_BYTE_BINARY);
    final Graphics g = mask.getGraphics();
    g.fillRect(sx1, sy1, (int) swidth, (int) sheight);
    drawImage(img, mask, tx, null, observer);
    g.dispose();
    return true;
}

From source file:FirstStatMain.java

private static BufferedImage getScreenShot(Component com) {
    BufferedImage image = new BufferedImage(com.getWidth(), com.getHeight(), BufferedImage.TYPE_INT_RGB);
    com.paint(image.getGraphics());
    return image;
}