If I open a browser and copy all of the page's text and images (CTRL+A), and then paste into Microsoft Word for example, both the text and images will be pasted.
I'm trying to write Java code that extracts the text and all the images from the clipboard contents in order to use the text/images within the program, such as displaying the image in a GUI later with supporting text.
Right now my code successfully extracts text from clipboard contents containing both text and images, but the image portion fails. The image code only works if the clipboard content contains a single image (such as pressing Print Screen). Otherwise it says:
java.awt.datatransfer.UnsupportedFlavorException: Image
at sun.awt.datatransfer.SunClipboard.getData(SunClipboard.java:220)
at Filter.main(Filter.java:28)
How do I alter this code so that text is stored in a String variable, and all images are stored in an image array? Anything helps, thanks.
public class Filter {
public static void main(String[] args) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String result;
try {
result = (String) clipboard.getData(DataFlavor.stringFlavor);
System.out.println(result);
} catch (Exception ex) {}
try {
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
File file = new File("C:\\Users\\ME\\Desktop\\image.jpg");
ImageIO.write(image, "jpg", file);
}
//getData throws this.
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
You don't. You inspect the contents of clipboard for the best way to retrieve it, for example..
Selecting all the contents of a web page and copying it, then running...
produces..
Now, you need to pick one which will be most useful to you, maybe something like...
Which just happens to return a
String
representation of the html/text content, because, lets face it, that's all a web page actually is.You'll need to parse the page for appropriate resources and download them manually