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.openmicroscopy.shoola.agents.measurement.view.IntensityResultsView.java

/** Saves the results of the table to an Excel file. */
private void saveResults() {
    FileChooser chooser = view.createSaveToExcelChooser();

    if (chooser.showDialog() != JFileChooser.APPROVE_OPTION)
        return;/*from ww  w .ja va  2 s .  c  om*/
    File file = chooser.getFormattedSelectedFile();
    ExcelWriter writer = null;
    try {
        String filename = file.getAbsolutePath();
        writer = new ExcelWriter(filename);
        writer.openFile();
        writer.createSheet("Intensity Results");
        writer.writeTableToSheet(0, 0, resultsModel);
        BufferedImage originalImage = model.getRenderedImage();
        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.setAttributes(MeasurementAttributes.SHOWID, false);
        try {
            if (image != null) {
                model.getDrawingView().print(image.getGraphics());
                writer.addImageToWorkbook("ThumbnailImage", image);
                int col = writer.getMaxColumn(0);
                writer.writeImage(0, col + 1, 256, 256, "ThumbnailImage");
            }
        } catch (Exception e) {
            Logger logger = MeasurementAgent.getRegistry().getLogger();
            logger.error(this, "Cannot write Image: " + e.toString());
        }
        writer.close();

    } catch (IOException e) {
        Logger logger = MeasurementAgent.getRegistry().getLogger();
        logger.error(this, "Cannot save ROI results: " + e.toString());

        UserNotifier un = MeasurementAgent.getRegistry().getUserNotifier();
        un.notifyInfo("Save Results",
                "An error occurred while trying to" + " save the data.\nPlease try again.");
        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:org.deegree.ogcwebservices.wms.dataaccess.ID2PInterpolation.java

public BufferedImage perform(GetLegendGraphic glg) {

    BufferedImage bi = new BufferedImage(150, colorMap.size() * 25, BufferedImage.TYPE_4BYTE_ABGR);
    Iterator<double[]> iterator = colorMap.keySet().iterator();
    List<double[]> list = new ArrayList<double[]>(colorMap.size());

    while (iterator.hasNext()) {
        double[] ds = iterator.next();
        list.add(ds);//w  w  w . j  av a 2 s.  c  o m
    }

    for (int i = list.size() - 1; 0 <= i; i--) {
        for (int j = 0; j < i; j++) {
            if (list.get(j + 1)[0] < list.get(j)[0]) {
                double[] ds = list.get(j + 1);
                list.set(j + 1, list.get(j));
                list.set(j, ds);
            }
        }
    }

    int i = 0;
    Graphics g = bi.getGraphics();
    for (double[] ds : list) {
        Color color = colorMap.get(ds);
        g.setColor(color);
        g.fillRect(2, 2 + i * 25, 20, 20);
        g.setColor(Color.BLACK);
        g.drawRect(2, 2 + i * 25, 20, 20);
        g.drawString(Double.toString(ds[0]) + " - " + Double.toString(ds[1]), 25, 17 + i * 25);
        i++;
    }
    g.dispose();
    return bi;

}

From source file:nl.softwaredesign.exporter.ODTExportFormat.java

/**
 * TODO Move to utility class?/*w  ww .java2 s .  c  om*/
 * Extract the content data (bytes) from the given image.
 * @param icon image to get bytes for
 * @param format desired format for image
 * @param background Color to use as background if transparency in image
 * @param width Desired width of the image in the byte array
 * @param height Desired width of the image in the byte array
 * @return the bytes of the image
 * @throws IOException
 */
private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height)
        throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = (ImageWriter) writers.next();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(output);
    writer.setOutput(ios);
    BufferedImage img;
    if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }
    WaitingObserver observer = new WaitingObserver();
    if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) {
        try {
            observer.waitForDone();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new byte[0];
        }
    }
    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img),
            writer.getDefaultWriteParam());
    if (format.equalsIgnoreCase("jpg")) {
        Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(72));
        jfif.setAttribute("Ydensity", Integer.toString(72));
        jfif.setAttribute("resUnits", "1");
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
    } else {
        double dotsPerMilli = 7.2 / 2.54;
        IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
        horiz.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
        vert.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode dim = new IIOMetadataNode("Dimension");
        dim.appendChild(horiz);
        dim.appendChild(vert);
        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
        root.appendChild(dim);
        metadata.mergeTree("javax_imageio_1.0", root);
    }

    writer.write(null, new IIOImage(img, null, metadata), null);
    return output.toByteArray();
}

From source file:UserInterface.GarbageCollectorRole.GarbageCollectorWorkAreaJPanel.java

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

From source file:net.chris54721.infinitycubed.data.Account.java

public void fetchSkin(boolean update) {
    if (nickname != null) {
        LogHelper.info("Fetching skin for player " + getNickname());
        BufferedImage skin = Utils.toBufferedImage(Utils.getImageResource("steve"));
        FileInputStream skinStream = null;
        boolean fetch = true;
        try {//from w  ww  .ja  v a 2s .c o m
            File skinFile = Resources.getFile(Resources.ResourceType.SKIN, getNickname() + ".png");
            if (update) {
                URL skinURL = Resources.getUrl(Resources.ResourceType.SKIN, getNickname() + ".png");
                Downloadable skinDownloadable = new Downloadable(skinURL, skinFile);
                if (!skinDownloadable.download())
                    fetch = false;
            } else if (!skinFile.isFile())
                fetch = false;
            if (fetch) {
                skinStream = new FileInputStream(skinFile);
                skin = ImageIO.read(skinStream);
                BufferedImage head = skin.getSubimage(8, 8, 8, 8);
                BufferedImage mask = skin.getSubimage(40, 8, 8, 8);
                skin = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
                Graphics resultG = skin.getGraphics();
                resultG.drawImage(head, 0, 0, null);
                resultG.drawImage(mask, 0, 0, null);
            }
            this.skin = skin;
            this.skinHead = skin.getScaledInstance(32, 32, Image.SCALE_DEFAULT);
        } catch (Exception e) {
            LogHelper.error("Couldn't fetch player skin", e);
        } finally {
            if (skinStream != null)
                IOUtils.closeQuietly(skinStream);
        }
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

protected BufferedImage getScaledImage(int width, int height) {
    BufferedImage tempImg = ImageUtils.createCompatibleBufferedImage(width, height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) tempImg.getGraphics();
    g2d.setColor(new Color(35, 125, 0));
    g2d.fillRect(0, 0, tempImg.getWidth(null), tempImg.getHeight(null));
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.drawImage(mBuffer, 0, 0, width, height, 0, 0, mBuffer.getWidth(), mBuffer.getHeight(), null);
    g2d.dispose();/*w w  w  .ja  v  a  2  s  . c  o m*/
    return tempImg;
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

protected BufferedImage getImage() {
    BufferedImage tempImg = ImageUtils.createCompatibleBufferedImage(mapDim.width, mapDim.height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) tempImg.getGraphics();
    g2d.setColor(new Color(35, 125, 0));
    g2d.fillRect(0, 0, tempImg.getWidth(null), tempImg.getHeight(null));
    g2d.drawImage(mBuffer, 0, 0, null);//from   w w w .  j ava2s  .  c o  m
    g2d.dispose();
    return tempImg;
}

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

@Override
public void actionPerformed(ActionEvent e) {
    ReportTableTab activeTab = getActiveTab();
    if (e.getActionCommand() != null && activeTab != null) {
        if (e.getActionCommand().equals("Copy")) {
            activeTab.transferSelection(ReportTableTab.TRANSFER_TYPE.COPY_TO_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("BBCopy")) {
            activeTab.transferSelection(ReportTableTab.TRANSFER_TYPE.CLIPBOARD_BB);
        } else if (e.getActionCommand().equals("Cut")) {
            activeTab.transferSelection(ReportTableTab.TRANSFER_TYPE.CUT_TO_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("Paste")) {
            activeTab.transferSelection(ReportTableTab.TRANSFER_TYPE.FROM_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("Delete")) {
            activeTab.deleteSelection(true);
        } else if (e.getActionCommand().equals("Find")) {
            BufferedImage back = ImageUtils.createCompatibleBufferedImage(3, 3, BufferedImage.TRANSLUCENT);
            Graphics g = back.getGraphics();
            g.setColor(new Color(120, 120, 120, 120));
            g.fillRect(0, 0, back.getWidth(), back.getHeight());
            g.setColor(new Color(120, 120, 120));
            g.drawLine(0, 0, 3, 3);//from w  w w. ja va  2  s. c om
            g.dispose();
            TexturePaint paint = new TexturePaint(back,
                    new Rectangle2D.Double(0, 0, back.getWidth(), back.getHeight()));
            jxSearchPane.setBackgroundPainter(new MattePainter(paint));
            DefaultListModel model = new DefaultListModel();

            for (int i = 0; i < activeTab.getReportTable().getColumnCount(); i++) {
                TableColumnExt col = activeTab.getReportTable().getColumnExt(i);
                if (col.isVisible()) {
                    if (!col.getTitle().equals("Status") && !col.getTitle().equals("Typ")
                            && !col.getTitle().equals("Sonstiges")) {
                        model.addElement(col.getTitle());
                    }
                }
            }
            jXColumnList.setModel(model);
            jXColumnList.setSelectedIndex(0);
            jxSearchPane.setVisible(true);
        }
    }
}

From source file:rems.Program.java

public static String formatDtSt(ResultSet dtst, String rptTitle, String[] colsToGrp, String[] colsToCnt,
        String[] colsToSum, String[] colsToAvrg, String[] colsToFrmt) {
    try {//from  ww  w .java  2s. c o  m
        DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
        DecimalFormat myFormatter2 = new DecimalFormat("###,##0");
        String finalStr = rptTitle.toUpperCase();
        finalStr += "\r\n\r\n";
        ResultSetMetaData dtstmd = dtst.getMetaData();
        dtst.last();
        int ttlRws = dtst.getRow();
        dtst.beforeFirst();
        int colCnt = dtstmd.getColumnCount();

        long[] colcntVals = new long[colCnt];
        double[] colsumVals = new double[colCnt];
        double[] colavrgVals = new double[colCnt];
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int e = 0; e < colCnt; e++) {
            int colLen = dtstmd.getColumnName(e + 1).length();
            if (colLen >= 3) {
                if (Program.mustColBeFrmtd(String.valueOf(e), colsToFrmt) == true) {
                    finalStr += StringUtils.leftPad(dtstmd.getColumnName(e + 1).substring(0, colLen - 2).trim(),
                            colLen, ' ');
                } else {
                    finalStr += StringUtils.leftPad(dtstmd.getColumnName(e + 1).substring(0, colLen - 2),
                            colLen, ' ');
                }
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        String[][] prevRowVal = new String[ttlRws][colCnt];
        for (int i = 0; i < ttlRws; i++) {
            String[][] lineFormat = new String[colCnt][];
            dtst.next();
            for (int a = 0; a < colCnt; a++) {
                double nwval = 0;
                prevRowVal[i][a] = dtst.getString(a + 1);

                boolean mstgrp = mustColBeGrpd(String.valueOf(a), colsToGrp);
                if (mustColBeCntd(String.valueOf(a), colsToCnt) == true) {
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colcntVals[a] += 1;
                    }
                } else if (mustColBeSumd(String.valueOf(a), colsToSum) == true) {
                    nwval = Double.parseDouble(dtst.getString(a + 1));
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colsumVals[a] += nwval;
                    }
                } else if (mustColBeAvrgd(String.valueOf(a), colsToAvrg) == true) {
                    nwval = Double.parseDouble(dtst.getString(a + 1));
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colcntVals[a] += 1;
                        colsumVals[a] += nwval;
                    }
                }

                int colLen = dtstmd.getColumnName(a + 1).length();
                String[] arry;
                BufferedImage bi;
                Graphics g; // stands for Buffered Image Graphics
                Toolkit toolkit;
                MediaTracker tracker;
                if (colLen >= 3) {
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1)))
                            && (mustColBeGrpd(String.valueOf(a), colsToGrp) == true)) {
                        toolkit = Toolkit.getDefaultToolkit();
                        Image img = toolkit.getImage(Global.appStatPath + "/staffs.png");
                        Font nwFont = new Font("Courier New", 11, Font.PLAIN);
                        bi = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
                        g = bi.getGraphics();
                        float ght = (float) g.getFontMetrics(nwFont).stringWidth(
                                StringUtils.rightPad(dtstmd.getColumnName(a + 1).trim(), colLen, '='));
                        float ght1 = (float) g.getFontMetrics(nwFont).stringWidth("=");
                        arry = breakDownStr("    ", colLen, 25, g, ght - ght1);
                    } else {
                        toolkit = Toolkit.getDefaultToolkit();
                        Image img = toolkit.getImage(Global.appStatPath + "/staffs.png");
                        Font nwFont = new Font("Courier New", 11, Font.PLAIN);
                        bi = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
                        g = bi.getGraphics();
                        float ght = (float) g.getFontMetrics(nwFont).stringWidth(
                                StringUtils.rightPad(dtstmd.getColumnName(a + 1).trim(), colLen, '='));
                        float ght1 = (float) g.getFontMetrics(nwFont).stringWidth("=");
                        arry = breakDownStr(dtst.getString(a + 1), colLen, 25, g, ght - ght1);
                    }
                    lineFormat[a] = arry;
                }
            }
            String frshLn = "";
            for (int c = 0; c < 25; c++) {
                String frsh = "|";
                for (int b = 0; b < colCnt; b++) {
                    int colLen = dtstmd.getColumnName(b + 1).length();
                    if (colLen >= 3) {
                        if (Program.mustColBeFrmtd(String.valueOf(b), colsToFrmt) == true) {
                            double num = Double.parseDouble(lineFormat[b][c].trim());
                            if (!lineFormat[b][c].trim().equals("")) {
                                frsh += StringUtils.leftPad(myFormatter.format(num), colLen, ' ').substring(0,
                                        colLen);//.trim().PadRight(60, ' ')
                            } else {
                                frsh += lineFormat[b][c].substring(0, colLen); //.trim().PadRight(60, ' ')
                            }
                        } else {
                            frsh += lineFormat[b][c].substring(0, colLen); //.trim().PadRight(60, ' ')
                        }
                        frsh += "|";
                    }
                }
                String nwtst = frsh;
                frsh += "\r\n";
                if (nwtst.replace("|", " ").trim().equals("")) {
                    c = 24;
                } else {
                    frshLn += frsh;
                }
            }
            finalStr += frshLn;
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        //Populate Counts/Sums/Averages
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                if (mustColBeCntd(String.valueOf(f), colsToCnt) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Count = " + StringUtils
                                .leftPad(myFormatter2.format(colcntVals[f]), colLen, ' ').substring(0, colLen);
                    } else {
                        finalStr += "Count = " + StringUtils
                                .rightPad(String.valueOf(colcntVals[f]), colLen, ' ').substring(0, colLen);
                    }
                } else if (mustColBeSumd(String.valueOf(f), colsToSum) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Sum = " + StringUtils
                                .leftPad(myFormatter.format(colsumVals[f]), colLen, ' ').substring(0, colLen);
                    } else {
                        finalStr += "Sum = " + StringUtils.rightPad(String.valueOf(colsumVals[f]), colLen, ' ')
                                .substring(0, colLen);
                    }
                } else if (mustColBeAvrgd(String.valueOf(f), colsToAvrg) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Average = " + StringUtils
                                .leftPad((myFormatter.format(colsumVals[f] / colcntVals[f])), colLen, ' ')
                                .substring(0, colLen);
                    } else {
                        finalStr += "Average = " + StringUtils
                                .rightPad((String.valueOf(colsumVals[f] / colcntVals[f])), colLen, ' ')
                                .substring(0, colLen);
                    }
                } else {
                    finalStr += StringUtils.rightPad(" ", colLen, ' ').substring(0, colLen);
                }
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("-", colLen, '-').substring(0, colLen);
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        return finalStr;
    } catch (SQLException ex) {
        return "";
    } catch (NumberFormatException ex) {
        return "";
    }
}

From source file:au.org.ala.biocache.web.WMSController.java

public static ImgObj create(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    return new ImgObj(g, img);
}