Screenshot based on JPanel location and size - java

I'm trying to take a screenshot of what's behind of a JPanel but i get a black image after saving it.
Here's the code:
private void takeScreenshot(String print){
JFileChooser c = new JFileChooser(getRealDesktop());
FileFilter jpg = new FileNameExtensionFilter(".jpg", ImageIO.getReaderFileSuffixes());
FileFilter jpeg = new FileNameExtensionFilter(".jpeg", ImageIO.getReaderFileSuffixes());
FileFilter png = new FileNameExtensionFilter(".png", ImageIO.getReaderFileSuffixes());
c.setFileFilter(png);
c.setFileFilter(jpeg);
c.setFileFilter(jpg);
c.showSaveDialog(this);
if(c.getSelectedFile() != null){
String ssLoc = c.getSelectedFile().getAbsolutePath()+c.getFileFilter().getDescription();
System.out.println(ssLoc);
BufferedImage bufImg = new BufferedImage(ssWindow.getSize().width, ssWindow.getSize().height,BufferedImage.TYPE_INT_RGB);
ssWindow.paint(bufImg.createGraphics());
File imageFile = new File(ssLoc);
try{
imageFile.createNewFile();
ImageIO.write(bufImg, "JPG", imageFile);
}catch(Exception ex){
System.err.println(ex);
}
}
}
And the press action button looks like this:
this.setVisible(false);
takeScreenshot("ssTake");
this.setVisible(true);
How can make this work?

Thanks, Gilbert Le Blanc.
I reworked a bit the code to use the robot for this and now the code looks like this:
private void takeScreenshot(String print){
JFileChooser c = new JFileChooser(getRealDesktop());
FileFilter jpeg = new FileNameExtensionFilter("JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)", "jpg", "jpeg", "jpe", "jfif");
c.setFileFilter(jpeg);
c.showSaveDialog(this);
if(c.getSelectedFile() != null){
ssLoc = c.getSelectedFile().getAbsolutePath()+".jpg";
try {
Thread.sleep(150);
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(ssWindow.getX(),ssWindow.getY(),ssWindow.getWidth(),ssWindow.getHeight()));
ImageIO.write(screenShot, "JPG", new File(ssLoc));
System.out.println(print);
} catch (AWTException | IOException | InterruptedException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

How can I fix my code so that it contains both a "save" and "save as" functions?

I have two buttons in a menubar that contains both a save and save as button. However, I currently have the code for both of them the same and it does the save as currently with prompting the user where they want to save. I want the save button to only save without prompting for the dialog unless the file doesn't yet exist.
I've tried fiddling around with the code to try and figure out a workaround, but have not figure it out.
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
The code currently does the exact same save function for each save button. I want it to only prompt for the save as button.
You need to have a File instance field in your class that is initially assigned to null. When you read in a File or when you do your first save, then this field is assigned to that File. When the save button is pressed, then you check if the field is null, and if so, show the dialog as you would for the save-as button. If the field is not null, then you simply write the file to disk using the data that you have and that File.
for example (code not tested):
// a private instance field
private File myFile = null;
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (myFile == null) {
saveAs();
} else {
writeFile(myFile);
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
saveAs();
}
});
private void writeFile(File file) {
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
private void saveAs() {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
myFile = file; // !!
writeFile(file);
}

Image didn't load in JPanel

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

Swing: how get active JInternalFrame

I have problem with getting active JInternalFrame. I need to indicate an active ImageInternalFrame(my class, thats extend JInternalFrame) because I will perform some operations on it. I do not know how to solve it, can somebody help me?
Here is my code:
public class MainFrame extends javax.swing.JFrame {
ArrayList <ImageInternalFrame> imageInternalFrameList = new ArrayList();
private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filePath = f.getPath();
BufferedImage bufferedImage;
ImageInternalFrame imageInternalFrame;
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
if(type.equals("image")){
bufferedImage = null;
try {
bufferedImage = ImageIO.read(new File(filePath));
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
imageInternalFrame = new ImageInternalFrame(filePath);
imageInternalFrame.setSize( bufferedImage.getWidth(), bufferedImage.getHeight() );
imageInternalFrame.setVisible(true);
imageInternalFrame.setLocation(imageInternalFrameList.size() * 25 , imageInternalFrameList.size() * 25);
add(imageInternalFrame);
imageInternalFrameList.add(imageInternalFrame);
}
else{
JOptionPane.showMessageDialog(null, "It's NOT an image");
}}
public class ImageInternalFrame extends javax.swing.JInternalFrame {
public ImageInternalFrame( String imagePath ) {
initComponents();
setImage(imagePath);
}
public void setImage(String imagePath){
imageLabel.setIcon( new ImageIcon(imagePath) );
imageLabel.paintImmediately(imageLabel.getVisibleRect());
}
}
You can use the getSelectedFrame() method of your JDesktop class.
imageLabel.setIcon( new ImageIcon(imagePath) );
imageLabel.paintImmediately(imageLabel.getVisibleRect());
Don't use paintImmeditately. Swing will automatically schedule the repainting of the label when you change the Icon.

Capture a specified area of screen using java

I am implementing a screenshot capture in my Java web Application Which Is Already Working. I however have an issue with the screenshot because the Image is Taken for the entire Screen:
As you can see this is the entire screen, I just want to capture the area with the graphs(the White area). The Code I am using to capture this screen is:
public void captureGraphs() {
try {
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(size));
File f = new File("C:/capture");
if (!f.exists()) {
f.mkdir();
}
File[] flist = f.listFiles();
for (File flist1 : flist) {
flist1.delete();
}
ImageIO.write(img, "JPG", new File("C:/capture/screenShot.jpg"));
System.out.println("Capture Successfull");
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_INFO,
"Successful!",
"You have successfully taken a snapshot. Thank You"));
} catch (HeadlessException e) {
System.out.println(e.getMessage());
} catch (AWTException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Is there any way I can change this code to capture the Mid Part only holding the graphs??

Append Images to RTF document

I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.

Categories