Example usage for java.awt Graphics2D drawImage

List of usage examples for java.awt Graphics2D drawImage

Introduction

In this page you can find the example usage for java.awt Graphics2D drawImage.

Prototype

public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer);

Source Link

Document

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

Usage

From source file:com.github.dactiv.fear.service.service.account.AccountService.java

/**
 * ??//from   ww  w  . jav a2s.  c o m
 *
 * @param sourcePath   ?
 * @param targetPath   ??
 * @param portraitSize ?
 *
 * @throws IOException
 */
private String scaleImage(String sourcePath, String targetPath, PortraitSize portraitSize) throws IOException {
    InputStream inputStream = new FileInputStream(sourcePath);

    BufferedImage source = ImageIO.read(inputStream);
    ColorModel targetColorModel = source.getColorModel();

    inputStream.close();

    int width = portraitSize.getWidth();
    int height = portraitSize.getHeight();

    BufferedImage target = new BufferedImage(targetColorModel,
            targetColorModel.createCompatibleWritableRaster(width, height),
            targetColorModel.isAlphaPremultiplied(), null);

    Image scaleImage = source.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    Graphics2D g = target.createGraphics();
    g.drawImage(scaleImage, 0, 0, width, height, null);
    g.dispose();

    String result = targetPath + portraitSize.getName();
    FileOutputStream fileOutputStream = new FileOutputStream(result);
    ImageIO.write(target, PORTRAIT_PIC_TYPE, fileOutputStream);

    fileOutputStream.close();

    return result;
}

From source file:edu.ku.brc.ui.IconManager.java

/**
 * Gets a scaled icon and if it doesn't exist it creates one and scales it
 * @param icon image to be scaled/*from ww  w.  j  a v a 2  s  . c  o m*/
 * @param iconSize the icon size (Std)
 * @param scaledIconSize the new scaled size in pixels
 * @return the scaled icon
 */
public Image getFastScale(final ImageIcon icon, final IconSize iconSize, final IconSize scaledIconSize) {
    if (icon != null) {
        int width = scaledIconSize.size();
        int height = scaledIconSize.size();

        if ((width < 0) || (height < 0)) { //image is nonstd, revert to original size
            width = icon.getIconWidth();
            height = icon.getIconHeight();
        }

        Image imgMemory = createImage(icon.getImage().getSource());
        //make sure all pixels in the image were loaded
        imgMemory = new ImageIcon(imgMemory).getImage();

        BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(imgMemory, 0, 0, width, height, null);
        graphics2D.dispose();

        imgMemory = thumbImage;
        return imgMemory;

    }
    //else
    log.error("Couldn't find icon [" + iconSize + "] to scale to [" + scaledIconSize + "]");
    return null;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAMediaFileManagerImpl.java

private void updateThumbnail(MediaFile mediaFile) {
    try {//  w w w . j  a va2 s . c om
        FileContentManager cmgr = WebloggerFactory.getWeblogger().getFileContentManager();
        FileContent fc = cmgr.getFileContent(mediaFile.getWeblog(), mediaFile.getId());
        BufferedImage img = null;

        img = ImageIO.read(fc.getInputStream());

        // determine and save width and height
        mediaFile.setWidth(img.getWidth());
        mediaFile.setHeight(img.getHeight());
        strategy.store(mediaFile);

        int newWidth = mediaFile.getThumbnailWidth();
        int newHeight = mediaFile.getThumbnailHeight();

        // create thumbnail image
        Image newImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage tmp = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = tmp.createGraphics();
        g2.drawImage(newImage, 0, 0, newWidth, newHeight, null);
        g2.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tmp, "png", baos);

        cmgr.saveFileContent(mediaFile.getWeblog(), mediaFile.getId() + "_sm",
                new ByteArrayInputStream(baos.toByteArray()));

    } catch (Exception e) {
        log.debug("ERROR creating thumbnail", e);
    }
}

From source file:gg.msn.ui.panel.MainPanel.java

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    super.paintComponent(g2d);
    g2d.setRenderingHints(/*from w  w  w.  j  a  v  a 2  s.c  om*/
            new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR));

    try {

        ImageIcon icon = ThemeManager.getTheme().get(ThemeManager.MAIN_BACKGROUND);

        if (icon != null) {
            Image image = icon.getImage();
            g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        } else {
            log.warn("image " + icon.getDescription() + " not Found");
        }

        icon = ThemeManager.getTheme().get(ThemeManager.MAIN_IMAGE);

        if (icon != null) {

            Image cartel = icon.getImage();
            g2d.drawImage(cartel, 0 - cartel.getWidth(this) / 10, getHeight() - cartel.getHeight(this), this);
        } else {
            log.warn("image " + icon.getDescription() + " not Found");
        }
    } catch (Exception e) {
        //            log.error(e);
    }
}

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//from  ww w  .  j  a v  a 2s.  c o  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:Starry.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);/*from   w  w w  .j av  a  2s  .  c  om*/
    w = getSize().width;
    h = getSize().height;
    Graphics2D g2;
    g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, w / 10);
    String s = new String("The Starry Night");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle r = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(w / 2 - (r.width / 2), h / 2 + (r.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
    g2.drawImage(img, r.x, r.y, r.width, r.height, this);

}

From source file:de.thm.arsnova.util.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString//from   w w  w. j  a  v a2  s  .co  m
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
                final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage originalImage = ImageIO.read(bais);
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append(IMAGE_PREFIX_START);
            result.append(extension);
            result.append(IMAGE_PREFIX_MIDDLE);

            ImageIO.write(newImage, extension, baos);

            baos.flush();

            result.append(Base64.encodeBase64String(baos.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Resize an image//from   w ww  .  j  a  va  2s . co  m
 * 
 * @param originalImage
 * @param width
 * @param height
 * @param type
 * @return
 */
private BufferedImage resize(BufferedImage originalImage, int width, int height, int type) {
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    try {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(originalImage, 0, 0, width, height, null);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }

    return resizedImage;
}

From source file:de.thm.arsnova.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString//w  w w .j av a  2  s. c  o  m
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
public String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append("data:image/");
            result.append(extension);
            result.append(";base64,");

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            ImageIO.write(newImage, extension, output);

            output.flush();
            output.close();

            result.append(Base64.encodeBase64String(output.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage());
            return null;
        }
    }
}