Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm automating our organization's supply ordering system. Under the current (paper) system, we need to attach a printout of the web page displaying the requested item if we're ordering off of a web site. The system I'm writing has a method to upload scanned documents, but I'd like to make it one-click operation instead of printing the web page, scanning it, then uploading the file of the scan.
I found this code to convert the page into an image, and it does work, but the image created is based off of the html (which makes sense), but not what is displayed in browser.
For example, I'm viewing this item:
When I run the url through the code, this is the returned image:
The project is Java web using a servlet. The servlet code:
try {
if (request.getParameter("formType").equalsIgnoreCase("addReference")) {
String url = request.getParameter("url");
BufferedImage bi = WebImage.create(url, 800, 600);
File tmpFile = new File("c:/testimages/url2img.png");
ImageIO.write(bi, "png", tmpFile);
} catch (Exception e) {
e.printStackTrace();
}
The code from the link above:
public abstract class WebImage {
static class Kit extends HTMLEditorKit {
#Override
public Document createDefaultDocument() {
HTMLDocument doc
= (HTMLDocument) super.createDefaultDocument();
doc.setTokenThreshold(Integer.MAX_VALUE);
doc.setAsynchronousLoadPriority(-1);
return doc;
}
}
public static BufferedImage create(String src, int width, int height) {
BufferedImage image = null;
JEditorPane pane = new JEditorPane();
Kit kit = new Kit();
pane.setEditorKit(kit);
pane.setEditable(false);
pane.setMargin(new Insets(0, 0, 0, 0));
try {
pane.setPage(src);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
Container c = new Container();
SwingUtilities.paintComponent(g, pane, c, 0, 0, width, height);
g.dispose();
} catch (Exception e) {
System.out.println(e);
}
return image;
}
}
Is there any way to return an image of the url as displayed by the browser?
You're using Java, so there's actually a really simple solution. Browser automation is a (mostly) solved problem with Selenium.
Here is some sample code, just note that it's not particularly robust if the page takes longer than usual to load but it should suffice to demonstrate the steps necessary to do what you want. Also note, that if this needs to run headlessly you might want to look into JBrowserDriver instead of the FireFox driver.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.com/I-Robot-Isaac-Asimov/dp/055338256X/ref=sr_1_2?ie=UTF8&qid=1496161782&sr=8-2&keywords=Asimov");
// This move is necessary, the original file is temporary and gets deleted after java exists
File resultingScreenshot = new File(System.getProperty("user.home"), "screenshot.png");
Files.move(screenshotFile, resultingScreenshot);
driver.quit();
System.out.println("The screenshot is found here: " + resultingScreenshot);
You need a fully fledged browser with all of its support for tonnes of web standards (HTML, CSS, JS) in order to achieve what you want. Otherwise you will often be capturing badly rendered images by a substandard web browser.
Have a look at Selenium as suggested by BCqrstoO.
Additionally there are also Headless Chrome which comes with Chrome 59 (yet to come for Windows)
or PhantomJS which unfortunately is no longer maintained, and therefore the ability to render latest and greatest pages will diminish over time.
Related
This question already has an answer here:
How to save a high DPI snapshot of a JavaFX Canvas
(1 answer)
Closed 7 years ago.
I'm trying to save a snapshot of my application to disk using JavaFX 2, which should be easy considering FX comes with a built-in snapshot function. It does work, however, the image is fuzzy. The application I'm building relies greatly on getting these images to save clear and crisp. Anyone know why this happens? Or how to fix it so it saves what I'm actually seeing when the app runs?
The top image is what saved to disk, the bottom is my app running:
My code for saving the scene is below:
try
{
WritableImage wi = new WritableImage((int) scene.getWidth(), (int) scene.getHeight());
WritableImage snapshot = scene.snapshot(wi);
File output = new File("Full.png");
ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", output);
} catch (IOException ex) {
ex.printStackTrace();
}
It looks as if you are running your code on a Mac with Retina display. If that is the case, the answer is here:
How to save a high DPI snapshot of a JavaFX Canvas
I'm doing a program to create a die (cube) with different image textures based on the input of the user (user choose images on a SWT GUI).
Once the user choose the images, it can visualize the dice on a separate dialog, and perform some rotate operations over it (see, after perform a small rotation to see three faces in the screenshots).
See screenshots: http://pastebin.com/XqJfXL6i
And my problem starts here: I want to save the content of the canvas (the dice with the background in its current form, after being rotated). I've been searching for several codes and I think that my problem is because my current canvas is an "on-screen" canvas and I need an off-screen canvas, which will allow to save the content.
My current code is the following:
http://pastebin.com/ZAv0ATJN
And.. here starts the problem. It throws this exception:
java.lang.IllegalStateException: Canvas3D: Not in off-screen mode
Concretely it fails in this line:
ImageComponent2D ic2d = canvas.getOffScreenBuffer();
As you can see there are several lines commented that I tried before, but they didn't work neither.
Any clue about how to do it?
Thanks!
Based on the comment provided by gouessej (thanks!) finally I use this code, which works fine for my doubt:
private void saveImage(String img) throws Exception {
FileOutputStream fileOut = new FileOutputStream(img);
Robot r = new Robot();
BufferedImage bi = r.createScreenCapture(new java.awt.Rectangle(
(int) frame.getLocationOnScreen().getX(), (int) frame
.getLocationOnScreen().getY(), frame.getBounds().width,
frame.getBounds().height));
ImageIO.write(bi, "jpeg", fileOut);
fileOut.flush();
fileOut.close();
}
I tried using Swing code in a JSP page. To my surprise it does work well and fine.
But I cannot judge if it is OK to use Swing with JSP?
Basically I want to display some pop up reports from Database. I was thinking to display a JFrame pop up/ applet to do the trick.
But do a web browser require any additional plugin for this?
Or is it fine to do such a thingy? Any guidance will be helpful.
Always remember that every java fragment you insert into your JSP is executed server-side, so it can be deceitful (it may seem to work in your development local machine, but it is only because the server and the client side are running on the same box).
The proper way to do this would be to write an Applet and include it into your page - this way, the browser will download it to client side and run it there. You should subclass JApplet (http://docs.oracle.com/javase/8/docs/api/javax/swing/JApplet.html) and then you will be able to use Swing components at will
The library works but your controls will never be shown at the client side (browser) but at the server (if it is that you have a working window service: Ms Windows, X11, Xorg,...).
I don't think that is a good practice and I would only use Swing library classes not to show GUI components but to use some classes to store special objects such as ImageIcon to store icons. But never to try to paint them.
I have a project where I use JLaTeXMath to generate a PNG within a JSP representing some math equations, in this context, I use javax.swing.JLabel to generate the image:
TeXFormula formula = new TeXFormula(texCode);
TeXIcon texImg = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 25);
BufferedImage img = new BufferedImage(texImg.getIconWidth(), texImg.getIconHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
texImg.paintIcon(new JLabel(),img.getGraphics(), 0, 0);
try {
OutputStream os = res.getOutputStream();
res.setContentType("image/png");
ImageIO.write(img, "png", os);
os.close();
res.flushBuffer();
} catch (Exception ex) {
log.warn("LaTeX renderer: " + ex.toString() + "\t" + "Msg: " + ex.getMessage());
return;
}
the JSP would run on the server,and probably display the GUI there,
but why would you want that? In the meantime, the person at the client
who submitted the request would be sitting there waiting for somebody
at the server end to close the Swing window so the JSP could get on
with its work.
So i would say that it is not feasible.
I have tried to devise a way to get a screenshot of a Java applet running in a browser, but I can't seem to get it working. I managed successfully to use cutycapt to get screenshots fine from "normal" websites, but I soon found out that qtwebkit which it seems to rely on for the rendering does not support java. I also tried IEcapt thinking that it would somehow inherit the Java rendering capabilities of IE on the system, but it does not work. Flash also does not seem to be working in IEcapt, and it has no flags for enabling plugins, so I am assuming the functionality is not there either.
Does anyone have any thoughts on how you could render something like an /index.jsp to an image from a Windows or Linux command line?
Selenium webdriver might be useful here:
http://docs.seleniumhq.org/projects/webdriver/
It is used primarily for test automation but it might be helpful.
It could be used, for example, like this:
import org.openqa.selenium.*;
WebDriver driver = new FirefoxDriver(); // create a Firefox webdriver instance
driver.get("http://www.google.com/"); // navigate to page
File screenshotFile = ((Screenshot)driver).getScreenshotAs(file); // capture screenshot
// and save to a file
// here you can trigger any necessary actions on the website:
Webelement element = driver.findElement(By.name("q")).sendKeys("xxxxx");
element.click();
new WebDriverWait(driver, 10)).until(ExpectedConditions.titleContains("xxxxx"));
// and capture a new screenshot once the content has changed
File xxxScreenshotFile = ((Screenshot)driver).getScreenshotAs(file);
Have you tried using java.awt.Robot?
Rectangle rect = yourGragphicsConfiguration.getBounds();
BufferedImage image = new Robot().createScreenCapture(rect);
If you know the position of your applet you might be able to get it with
BufferedImage dest = image.getSubimage(appletX, appletY, appletHeight, appletWidth);
You can take a screenshot of Swing/AWT component.
This can be done in 2 ways. In both cases the component must be visible.
Without the robot use:
BufferedImage image = new BufferedImage(component.getWidth(),
component.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
component.paint(g);
With the robot use:
In this case the screenshot of area in which this component is situated will be made. That is, if the component overlaps another application window then the screenshot will contain an area of this another window.
Point point = new Point(0, 0);
SwingUtilities.convertPointToScreen(point, component);
Rectangle region = component.getBounds();
region.x = point.x;
region.y = point.y;
BufferedImage image= new Robot().createScreenCapture(region);
This information is taken from the article: Frequently Asked Questions during Java applet development
Is it possible to take a screen capture of a specific application/exe launched on Windows in Java?
I tried this code but it does not take a capture of the application itself and return a black picture:
try {
...
Robot robot = new Robot();
Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(captureSize);
ImageIO.write(bufferedImage,"png",myFile);
...
} catch(AWTException e) {
System.err.println("call a doc!");
}
This is why I think that forcing a screenshot linked with the process launched may solve the problem.
Or maybe they are other ways to take a capture of the displayed screen? (if yes could you please show me some working code?)