How to capture the screenshot of a specific element rather than entire page using JXBrowser?

196 Views Asked by At

What I wanted is just to capture a part of the page or perhaps just on specific element based on ID or any specific element locator. (For example, I wish to capture the picture with image id ="logo")

Is there any way to capture a screenshot by selected item or element?

            Browser browser = new Browser();
            BrowserView view = new BrowserView(browser);
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.add(view, BorderLayout.CENTER);
            frame.setSize(700, 500);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            browser.loadURL("https://cafemmo.club/");
            TimeUnit.SECONDS.sleep(10);

browser.getDocument().findElement(By.cssSelector("#logo"));
1

There are 1 best solutions below

0
Vladyslav Lubenskyi On

There is no API to do it in one call. But the following approach should work:

  1. Take a snapshot of the whole page. This is described here: https://jxbrowser-support.teamdev.com/docs/6/guides/content.html#saving-web-page-to-png

  2. Obtain the bounds of the element inside of the page and manually cut this region out of the element. Here's how you can get the bounds: https://jxbrowser-support.teamdev.com/docs/6/guides/dom.html#getting-element-bounds

And in case you're using JxBrowser 7, they have introduced API to obtain raw bytes of an image in <img> tag: https://jxbrowser-support.teamdev.com/javadoc/7.21/com/teamdev/jxbrowser/dom/ImageElement.html#contents--