Why does my screenshot only show my desktop? - java

I want to take a screenshot of my screen while in Google Chrome but when my screenshot saves its only my desktop? Im on a mac btw
try {
Robot robot = new Robot();
String format = "jpg";
String fileName = "FullScreenshot." + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(fileName));
System.out.println("A full screenshot saved!");
} catch (AWTException | IOException ex) {
System.err.println(ex);
}

Related

ImageIO does not save screenshots

I am trying to get a screenshot of my desktop and save it in specific folder, for this purpose, I wrote following method:
class Test(){
public static String screenshot(String outDir){
try {
Robot robot = new Robot();
String format = ".png";
String fileName = String.valueOf(System.currentTimeMillis()) + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(outDir + fileName));
System.out.println("Success");
return outDir + fileName;
} catch (AWTException | IOException e) {
e.printStackTrace();
}
return null;
}
}
I was planning to use the code like so:
Test.screenshot("C:\\temp\\");
So the magic is it does not write the screenshot file in the specific folder, but if I remove file extension and explicitly hardcode the name of the file it writes the result.
However, this code works:
public static String screenshot(){
try {
Robot robot = new Robot();
String format = "jpg";
String fileName = "XXX." + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File("C:\\temp\\" + fileName));
System.out.println("Success");
return outDir + fileName;
} catch (AWTException | IOException e) {
e.printStackTrace();
}
return null;
}
What am I doing wrong here?
I have seen the javadoc. The problem is about the formatName, as doc say: formatName - a String containg the informal name of the format. => means that your format should only contain name, not include the dot (.). So that's why your hardcode run because your hardcode using the correct formatName

Black borders around png screenshot

Below are the codes i have written to take screenshot of an active window. However, im unsure why there are black borders surrounding the image. Please help and tell me if there is any mistakes in my codes.
Robot robot; //create robot instance
robot = new Robot(); //gets and saves a reference to a new Robot
robot.delay(3000); //delay robot for 3 seconds
//get dimensions of the bounding rectangle of the specified window
WinDef.HWND hwnd = User32.INSTANCE.GetForegroundWindow();
RECT WindowDimensions = new RECT();
//get screen coordinates of upper-left and lower-right corners of the window in dimensionsOfWindow
User32.INSTANCE.GetWindowRect(hwnd, WindowDimensions);
//capture image of only active window
BufferedImage screenFullImage = robot.createScreenCapture(WindowDimensions.toRectangle());
//write buffered image to file
try{
//File f = new File(dir + "\\screenshot " + createTimeStampStr() + ".png"); //file path of output
File f = new File("D:\\screenshot " + createTimeStampStr() + ".png"); //file path of output
ImageIO.write(screenFullImage, "png", f);
}catch(IOException e){
System.out.println("Error: " + e);
}

How to save svg or esp file in JavaPlot

I tried the code for saving png files found here and it works.
But I want to save a vector image, so I changed the terminal to: PostscriptTerminal and SVGTerminal. For the SVGTerminal the output in empty and when I use the PostscriptTerminal the code hangs at p.plot();
ImageTerminal png = new ImageTerminal();
PostscriptTerminal eps = new PostscriptTerminal();
SVGTerminal svg = new SVGTerminal();
File file = new File("D:/plot.eps");
try {
file.createNewFile();
eps.processOutput(new FileInputStream(file));
} catch (FileNotFoundException ex) {
System.err.print(ex);
} catch (IOException ex) {
System.err.print(ex);
}
PlotStyle myPlotStyle = new PlotStyle();
myPlotStyle.setStyle(Style.POINTS);
myPlotStyle.setPointType(7); // 7 - circle
myPlotStyle.setLineType(3); // blue color
JavaPlot p = new JavaPlot();
p.setPersist(false);
p.setTerminal(eps);
//p.setTitle(algorithm_name+" - "+problem_name, "Arial", 20);
p.getAxis("x").setLabel("X axis", "Arial", 15);
p.getAxis("y").setLabel("Y axis","Arial", 15);
p.setKey(JavaPlot.Key.TOP_RIGHT);
double[][] front = this.writeObjectivesToMatrix();
DataSetPlot s = new DataSetPlot(front);
s.setPlotStyle(myPlotStyle);
s.setTitle("");
p.addPlot(s);
p.plot(); //code hangs here if I use PostscriptTerminal
try {
//ImageIO.write(png.getImage(), "png", file); //works
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write (eps.getTextOutput());
//Close writer
writer.close();
} catch (IOException ex) {
System.err.print(ex);
}
I managed to save an .eps file. I only needed to add a file path in constructor and it worked.
PostscriptTerminal eps = new PostscriptTerminal("output.eps");
PlotStyle myPlotStyle = new PlotStyle();
myPlotStyle.setStyle(Style.POINTS);
myPlotStyle.setPointType(7); // 7 - circle
myPlotStyle.setLineType(3); // blue color
JavaPlot p = new JavaPlot();
p.setPersist(false);
p.setTerminal(eps);
p.getAxis("x").setLabel("X axis", "Arial", 15);
p.getAxis("y").setLabel("Y axis","Arial", 15);
p.setKey(JavaPlot.Key.TOP_RIGHT);
double[][] front = this.writeObjectivesToMatrix();
DataSetPlot s = new DataSetPlot(front);
s.setPlotStyle(myPlotStyle);
s.setTitle("");
p.addPlot(s);
p.plot();

How to upload bufferedImage without storing it in user's system?

I am a beginner in java, and I am trying to write a simple screen-capture program. I wrote a simple SWING desktop app with a button and a text-field, and what I am trying to do is, when a user clicks that button the app takes a snapshot of the screen using awt.Robot, and sends that image and the text to a PHP script on my server.
My snapshot function so far is:
private void takeSnapShot(){
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
File file = new File("screenshot_full.png");
ImageIO.write(bufferedImage, "png", file);
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
}
As you can see it's fairly simple so far, however I am not sure how to send that image to my PHP script without actually storing the image on user's PC.
Oh and I am using apache httpClient library for communicating to the web server. For the text I guess I can pass it in the URL as a get query, but I am not sure what to do about the image.
ImageIO.write can to an OutputStream of your choice.
So if you don't want to write the image to a File, you can simply write it to a different stream instead...
For example...
OutputStream os = null;
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
os = ...;
ImageIO.write(bufferedImage, "png", os);
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
os.close();
} catch (Exception exp) {
}
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, I have no idea where you're sending the data, so you'll need to define the OutputStream yourself.
If you have the memory for it, you could write it a ByteArrayOutputStream and then write this to whatever output stream you need in the future...
To slightly modify your existing method, perhaps you could use a temporarily file and then delete it when you are finished with it. Perhaps it might look something like:
private void takeSnapShot(){
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
File file = File.createTempFile(Long.toString(System.currentTimeMillis()), ".png");
ImageIO.write(bufferedImage, "png", file);
//send image
file.delete();
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
}
Another alternative would be to construct an int[][] from your BufferedImage which will hold the RGB values for every pixel of the image:
public int[][] getColors(final BufferedImage image){
assert image != null;
final int[][] colors = new int[image.getWidth()][image.getHeight()];
for(int x = 0; x < colors.length; x++)
for(int y = 0; y < colors[x].length; y++)
colors[x][x] = image.getRGB(x, y);
return colors;
}
I am a little unsure about what you hope to achieve; What do you plan on doing with the image?
Why don't you make this a WebsService and let your PHP consume it? You could send the binary data through the WebsService using some sort of Base64 encoder.
You could do this to get the bytes of the BufferedImage:
byte[] binaryData = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();

how to save the the image in folder on disk using java

I want to save the image on disk such as c:/images which is captured by webcam using java ..and again I want to display that image on JForm as a label...
is this possible using java and netbeans
I'm new in java
you can save image
private static void save(String fileName, String ext) {
File file = new File(fileName + "." + ext);
  BufferedImage image = toBufferedImage(file);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
and read image from disk and show into label as
File file = new File("image.gif");
image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
You can use BufferedImage to load an image from your hard disk :
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
Try this link for further information. Reading/Loading Images in Java
And this one for saving the image. Writing/Saving an Image
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
Pure Java, not third party library needed:
byte[] image = /*your image*/
String filePath = /*destination file path*/
File file = new File(filePath);
try (FileOutputStream fosFor = new FileOutputStream(file)) {
fosFor.write(image);
}
//Start Photo Upload with No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with No//

Categories