Example usage for java.awt.image BufferedImage TYPE_INT_ARGB

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

Introduction

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

Prototype

int TYPE_INT_ARGB

To view the source code for java.awt.image BufferedImage TYPE_INT_ARGB.

Click Source Link

Document

Represents an image with 8-bit RGBA color components packed into integer pixels.

Usage

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/*www .ja  v a2 s.co m*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

private static BufferedImage applyColorKeyMask(BufferedImage image, BufferedImage mask) throws IOException {
    int width = image.getWidth();
    int height = image.getHeight();

    // compose to ARGB
    BufferedImage masked = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    WritableRaster src = image.getRaster();
    WritableRaster dest = masked.getRaster();
    WritableRaster alpha = mask.getRaster();

    float[] rgb = new float[3];
    float[] rgba = new float[4];
    float[] alphaPixel = null;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            src.getPixel(x, y, rgb);//from   www.  j  a  v  a 2s .co m

            rgba[0] = rgb[0];
            rgba[1] = rgb[1];
            rgba[2] = rgb[2];
            alphaPixel = alpha.getPixel(x, y, alphaPixel);
            rgba[3] = 255 - alphaPixel[0];

            dest.setPixel(x, y, rgba);
        }
    }

    return masked;
}

From source file:com.imag.nespros.gui.plugin.GraphEditor.java

/**
 * create an instance of a simple graph with popup controls to create a
 * graph./*www . jav a 2  s.com*/
 *
 */
private GraphEditor(Simulation s) {
    simu = s;
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        Logger.getLogger(GraphEditor.class.getName()).log(Level.SEVERE, null, ex);
    }
    // create a simple graph for the demo
    graph = Topology.getInstance().getGraph();
    this.layout = new StaticLayout<Device, ComLink>(graph, new Transformer<Device, Point2D>() {
        @Override
        public Point2D transform(Device v) {
            Point2D p = new Point2D.Double(v.getX(), v.getY());
            return p;
        }
    }, new Dimension(600, 600));

    vv = new VisualizationViewer<Device, ComLink>(layout);
    vv.setBackground(Color.white);

    final Transformer<Device, String> vertexLabelTransformer = new Transformer<Device, String>() {
        @Override
        public String transform(Device d) {
            return d.getDeviceName();
        }
    };

    //vv.getRenderContext().setVertexLabelTransformer(MapTransformer.<Device, String>getInstance(
    //      LazyMap.<Device, String>decorate(new HashMap<Device, String>(), new ToStringLabeller<Device>())));
    vv.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);
    vv.getRenderContext().setEdgeLabelTransformer(new Transformer<ComLink, String>() {
        @Override
        public String transform(ComLink link) {
            return (link.getID() + ", " + link.getLatency());
        }
    });
    //float dash[] = {0.1f};
    //final Stroke edgeStroke = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 1.0f);
    final Stroke edgeStroke = new BasicStroke(3.0f);
    final Transformer<ComLink, Stroke> edgeStrokeTransformer = new Transformer<ComLink, Stroke>() {
        @Override
        public Stroke transform(ComLink l) {
            return edgeStroke;
        }
    };
    Transformer<ComLink, Paint> edgePaint = new Transformer<ComLink, Paint>() {
        public Paint transform(ComLink l) {
            if (l.isDown()) {
                return Color.RED;
            } else {
                return Color.BLACK;
            }
        }
    };
    vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
    vv.setVertexToolTipTransformer(vv.getRenderContext().getVertexLabelTransformer());
    vv.getRenderContext().setVertexIconTransformer(new CustomVertexIconTransformer());
    vv.getRenderContext().setVertexShapeTransformer(new CustomVertexShapeTransformer());

    vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {

        @Override
        public void paint(Graphics grphcs) {

            for (Device d : Topology.getInstance().getGraph().getVertices()) {
                int size = d.getOperators().size();
                MyLayeredIcon icon = d.getIcon();
                //if(icon == null) continue;
                icon.removeAll();
                if (size > 0) {
                    // the vertex icon                        
                    // Let's create the annotation image to be added to icon..
                    BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g = image.createGraphics();
                    g.setColor(Color.ORANGE);
                    g.fillOval(0, 0, 20, 20);
                    g.setColor(Color.BLACK);
                    g.drawString(size + "", 5, 13);
                    g.dispose();
                    ImageIcon img = new ImageIcon(image);
                    //Dimension id = new Dimension(icon.getIconWidth(), icon.getIconHeight());
                    //double x = vv.getModel().getGraphLayout().transform(d).getX();
                    //x -= (icon.getIconWidth() / 2);
                    //double y = vv.getModel().getGraphLayout().transform(d).getY();
                    //y -= (icon.getIconHeight() / 2);
                    //grphcs.drawImage(image, (int) Math.round(x), (int) Math.round(y), null);
                    icon.add(img);
                }
            }
        }

        @Override
        public boolean useTransform() {
            return false;
        }
    });

    Container content = getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);
    Factory<Device> vertexFactory = DeviceFactory.getInstance();
    Factory<ComLink> edgeFactory = ComLinkFactory.getInstance();

    final EditingModalGraphMouse<Device, ComLink> graphMouse = new EditingModalGraphMouse<>(
            vv.getRenderContext(), vertexFactory, edgeFactory);

    // Trying out our new popup menu mouse plugin...
    PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
    // Add some popup menus for the edges and vertices to our mouse plugin.
    JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
    JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu(frame);
    myPlugin.setEdgePopup(edgeMenu);
    myPlugin.setVertexPopup(vertexMenu);
    graphMouse.remove(graphMouse.getPopupEditingPlugin()); // Removes the existing popup editing plugin

    graphMouse.add(myPlugin); // Add our new plugin to the mouse  
    // AnnotatingGraphMousePlugin<Device,ComLink> annotatingPlugin =
    //   new AnnotatingGraphMousePlugin<>(vv.getRenderContext());
    //graphMouse.add(annotatingPlugin);
    // the EditingGraphMouse will pass mouse event coordinates to the
    // vertexLocations function to set the locations of the vertices as
    // they are created
    //        graphMouse.setVertexLocations(vertexLocations);
    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());

    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    //final ImageAtEdgePainter<String, String> imageAtEdgePainter = 
    //  new ImageAtEdgePainter<String, String>(vv, edge, image);
    final ScalingControl scaler = new CrossoverScalingControl();
    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(vv, instructions);
        }
    });
    JButton deploy = new JButton("Deploy");
    deploy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // OPMapping algo here
            if (simu == null) {
                return;
            }
            GraphUtil<Device, ComLink> util = new GraphUtil<>();
            for (EventProducer p : simu.getProducers()) {
                if (!p.isMapped()) {
                    JOptionPane.showMessageDialog(frame,
                            "Cannot map operators. Please deploy the producer: " + p.getName());
                    return;
                }
            }
            for (EventConsumer c : simu.getConsumers()) {
                if (!c.isMapped()) {
                    JOptionPane.showMessageDialog(frame,
                            "Cannot map operators. Please deploy the consumer: " + c.getName());
                    return;
                }
                System.out.println("-- Operator placement algorithm Greedy: " + c.getName() + " --");
                Solution init = util.initialMapping(c.getGraph());
                System.out.println(c.getGraph() + "\nInitial Mapping: " + init);
                OperatorMapping mapper = new OperatorMapping();
                long T1, T2;
                System.out.println("--- OpMapping Algo Greedy --- ");
                T1 = System.currentTimeMillis();
                Solution solution = mapper.opMapping(c.getGraph(), Topology.getInstance().getGraph(), init);
                T2 = System.currentTimeMillis();
                System.out.println(solution);
                System.out.println("Solution founded in: " + (T2 - T1) + " ms");
            }
            //                Solution init = util.initialMapping(EPGraph.getInstance().getGraph());
            //                System.out.println("Initial Mapping: " + init);
            //                OperatorMapping mapper = new OperatorMapping();
            //                long T1, T2;
            //                System.out.println("--- OpMapping Algo Greedy --- ");
            //                T1 = System.currentTimeMillis();
            //                Solution solution = mapper.opMapping(EPGraph.getInstance().getGraph(),
            //                        Topology.getInstance().getGraph(), init);
            //                T2 = System.currentTimeMillis();
            //                System.out.println(solution);
            //                System.out.println("Solution founded in: " + (T2 - T1) + " ms");
            vv.repaint();
        }
    });
    JButton run = new JButton("Run");
    run.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // run the simulation here
            System.out.println("Setting the simulation...");
            for (EventConsumer c : simu.getConsumers()) {

                for (EPUnit op : c.getGraph().getVertices()) {
                    if (op.isMapped()) {
                        op.openIOchannels();
                    } else {
                        JOptionPane.showMessageDialog(frame, "Cannot run, undeployed operators founded.");
                        return;
                    }
                }
            }
            //ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            System.out.println("Running the simulation...");
            //scheduledExecutorService.execute(runner);
            for (Device device : Topology.getInstance().getGraph().getVertices()) {
                if (!device.isAlive()) {
                    device.start();
                }
            }
            for (ComLink link : Topology.getInstance().getGraph().getEdges()) {
                if (!link.isAlive()) {
                    link.start();
                }
            }
            for (EventConsumer c : simu.getConsumers()) {
                for (EPUnit op : c.getGraph().getVertices()) {
                    if (op.isMapped() && op.getDevice() != null && !op.isAlive()) {
                        op.start();
                    }
                }
            }

        }
    });
    AnnotationControls<Device, ComLink> annotationControls = new AnnotationControls<Device, ComLink>(
            graphMouse.getAnnotatingPlugin());
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 0);
    slider.setMinorTickSpacing(5);
    slider.setMajorTickSpacing(30);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setLabelTable(slider.createStandardLabels(15));
    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider slider = (JSlider) e.getSource();
            if (!slider.getValueIsAdjusting()) {
                speedSimulation(slider.getValue());
            }
        }
    });
    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    JComboBox modeBox = graphMouse.getModeComboBox();
    controls.add(modeBox);
    controls.add(annotationControls.getAnnotationsToolBar());
    controls.add(slider);
    controls.add(deploy);
    controls.add(run);
    controls.add(help);
    content.add(controls, BorderLayout.SOUTH);
    /* Custom JPanels can be added here  */
    //
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //final GraphEditor demo = new GraphEditor();

}

From source file:net.yacy.cora.util.Html2Image.java

/**
 * render a html page with a JEditorPane, which can do html up to html v 3.2. No CSS supported!
 * @param url//from www . j  av a 2s.  c  o m
 * @param size
 * @throws IOException 
 */
public static void writeSwingImage(String url, Dimension size, File destination) throws IOException {

    // set up a pane for rendering
    final JEditorPane htmlPane = new JEditorPane();
    htmlPane.setSize(size);
    htmlPane.setEditable(false);
    final HTMLEditorKit kit = new HTMLEditorKit() {

        private static final long serialVersionUID = 1L;

        @Override
        public Document createDefaultDocument() {
            HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
            doc.setAsynchronousLoadPriority(-1);
            return doc;
        }

        @Override
        public ViewFactory getViewFactory() {
            return new HTMLFactory() {
                @Override
                public View create(Element elem) {
                    View view = super.create(elem);
                    if (view instanceof ImageView) {
                        ((ImageView) view).setLoadsSynchronously(true);
                    }
                    return view;
                }
            };
        }
    };
    htmlPane.setEditorKitForContentType("text/html", kit);
    htmlPane.setContentType("text/html");
    htmlPane.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
        }
    });

    // load the page
    try {
        htmlPane.setPage(url);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // render the page
    Dimension prefSize = htmlPane.getPreferredSize();
    BufferedImage img = new BufferedImage(prefSize.width, htmlPane.getPreferredSize().height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics graphics = img.getGraphics();
    htmlPane.setSize(prefSize);
    htmlPane.paint(graphics);
    ImageIO.write(img, destination.getName().endsWith("jpg") ? "jpg" : "png", destination);
}

From source file:org.dishevelled.brainstorm.BrainStorm.java

/**
 * Create and return a new hidden cursor, that is a fully transparent one pixel custom cursor.
 *
 * @return a new hidden cursor/* w w  w .j a  v  a 2  s .c om*/
 */
private Cursor createHiddenCursor() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension size = toolkit.getBestCursorSize(1, 1);
    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f));
    graphics.clearRect(0, 0, size.width, size.height);
    graphics.dispose();
    return toolkit.createCustomCursor(image, new Point(0, 0), "hiddenCursor");
}

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to PDF option in the context menu.
 *//*from  www  .  j a  va 2  s  .co  m*/
private void handleExportToPDF() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setSelectedExtensionFilter(
            new FileChooser.ExtensionFilter("Portable Document Format (PDF)", "pdf"));
    fileChooser.setTitle("Export to PDF");
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {

        try {

            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            PDDocument doc = new PDDocument();

            PDPage page = new PDPage(new PDRectangle((float) canvasPositionAndSize.totalWidth,
                    (float) canvasPositionAndSize.totalHeight));
            doc.addPage(page);

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            PDXObjectImage pdImage = new PDPixelMap(doc, image);
            contentStream.drawImage(pdImage, 0, 0);

            PDPageContentStream cos = new PDPageContentStream(doc, page);
            cos.drawXObject(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
            cos.close();

            doc.save(file);

        } catch (IOException | COSVisitorException ex) {
            Logger.getLogger(ChartViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
        (int)canvas.getHeight(), file);*/

        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
                (int)canvas.getHeight(), file);*/
    }
}

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

@RequestMapping(value = "/occurrences/legend", method = RequestMethod.GET)
public void pointLegendImage(
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "50") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "50") Integer heightObj,
        HttpServletResponse response) {//from   w  ww .  j  a va2 s.  co  m
    try {
        int width = widthObj.intValue();
        int height = heightObj.intValue();

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);

        } else {
            g.setPaint(Color.blue);
        }

        g.fillOval(0, 0, width, width);

        g.dispose();

        response.setContentType("image/png");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java

/**
 * Scales the signature image to fit the provided signature field dimensions,
 * preserving the aspect ratio/*from   w ww. j a  va2  s.c  o m*/
 * 
 * @param signatureImage
 * @param width
 * @param height
 * @return
 */
private BufferedImage scaleSignature(BufferedImage signatureImage, int width, int height) {
    if (signatureImage.getHeight() > height) {
        BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        AffineTransform at = new AffineTransform();
        at.scale(2.0, 2.0);
        AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        scaled = scaleOp.filter(signatureImage, scaled);
        return scaled;
    } else {
        return signatureImage;
    }
}

From source file:base.BasePlayer.ClusterTable.java

void addHeaderColumn(Object column) {
    Object[] obj = new Object[3];
    obj[0] = column;/*from  ww  w  .  j  a  va 2s .c  om*/
    obj[1] = (int) header.get(header.size() - 1)[1] + (int) header.get(header.size() - 1)[2];
    obj[2] = 100;
    header.add(obj);

    if ((int) obj[1] + (int) obj[2] > this.getWidth()) {
        if (bufImage.getWidth() != 1) {
            if (bufImage.getWidth() < (int) obj[1] + (int) obj[2]) {
                bufImage = MethodLibrary.toCompatibleImage(
                        new BufferedImage((int) width * 2, (int) height, BufferedImage.TYPE_INT_ARGB));
                buf = (Graphics2D) bufImage.getGraphics();
            }
        }
    }
    this.setPreferredSize(new Dimension((int) obj[1] + (int) obj[2], this.getHeight()));
    this.revalidate();
}

From source file:org.executequery.gui.browser.TableDataTab.java

private Object setTableResultsPanel(DatabaseObject databaseObject) {

    tableDataChanges.clear();//from www . j  a v  a  2 s  .c  om
    primaryKeyColumns.clear();
    foreignKeyColumns.clear();

    this.databaseObject = databaseObject;
    try {

        initialiseModel();
        tableModel.setCellsEditable(false);
        tableModel.removeTableModelListener(this);

        if (isDatabaseTable()) {

            DatabaseTable databaseTable = asDatabaseTable();
            if (databaseTable.hasPrimaryKey()) {

                primaryKeyColumns = databaseTable.getPrimaryKeyColumnNames();
                canEditTableLabel.setText("This table has a primary key(s) and data may be edited here");
            }

            if (databaseTable.hasForeignKey()) {

                foreignKeyColumns = databaseTable.getForeignKeyColumnNames();
            }

            if (primaryKeyColumns.isEmpty()) {

                canEditTableLabel.setText("This table has no primary keys defined and is not editable here");
            }

            canEditTableNotePanel.setVisible(alwaysShowCanEditNotePanel);
        }

        if (!isDatabaseTable()) {

            canEditTableNotePanel.setVisible(false);
        }

        Log.debug("Retrieving data for table - " + databaseObject.getName());

        ResultSet resultSet = databaseObject.getData(true);
        tableModel.createTable(resultSet);
        if (table == null) {

            createResultSetTable();
        }
        tableModel.setNonEditableColumns(primaryKeyColumns);

        TableSorter sorter = new TableSorter(tableModel);
        table.setModel(sorter);
        sorter.setTableHeader(table.getTableHeader());

        if (isDatabaseTable()) {

            SortableHeaderRenderer renderer = new SortableHeaderRenderer(sorter) {

                private ImageIcon primaryKeyIcon = GUIUtilities
                        .loadIcon(BrowserConstants.PRIMARY_COLUMNS_IMAGE);
                private ImageIcon foreignKeyIcon = GUIUtilities
                        .loadIcon(BrowserConstants.FOREIGN_COLUMNS_IMAGE);

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {

                    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) super.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);

                    Icon keyIcon = iconForValue(value);
                    if (keyIcon != null) {

                        Icon icon = renderer.getIcon();
                        if (icon != null) {

                            BufferedImage image = new BufferedImage(
                                    icon.getIconWidth() + keyIcon.getIconWidth() + 2,
                                    Math.max(keyIcon.getIconHeight(), icon.getIconHeight()),
                                    BufferedImage.TYPE_INT_ARGB);

                            Graphics graphics = image.getGraphics();
                            keyIcon.paintIcon(null, graphics, 0, 0);
                            icon.paintIcon(null, graphics, keyIcon.getIconWidth() + 2, 5);

                            setIcon(new ImageIcon(image));

                        } else {

                            setIcon(keyIcon);
                        }

                    }

                    return renderer;
                }

                private ImageIcon iconForValue(Object value) {

                    if (value != null) {

                        String name = value.toString();
                        if (primaryKeyColumns.contains(name)) {

                            return primaryKeyIcon;

                        } else if (foreignKeyColumns.contains(name)) {

                            return foreignKeyIcon;
                        }

                    }

                    return null;
                }

            };
            sorter.setTableHeaderRenderer(renderer);

        }

        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        scroller.getViewport().add(table);
        removeAll();

        add(canEditTableNotePanel, canEditTableNoteConstraints);
        add(scroller, scrollerConstraints);

        if (displayRowCount && SystemProperties.getBooleanProperty("user", "browser.query.row.count")) {

            add(rowCountPanel, rowCountPanelConstraints);
            rowCountField.setText(String.valueOf(sorter.getRowCount()));
        }

    } catch (DataSourceException e) {

        if (!cancelled) {

            addErrorLabel(e);

        } else {

            addCancelledLabel();
        }

    } finally {

        tableModel.addTableModelListener(this);
    }

    setTableProperties();
    validate();
    repaint();

    return "done";
}