I've a desktop java application that get images from the user clipboard ("paste" action), and I need to check their mime type before further processing (only jpg, png and gif are admitted).
I'm using this code to get the image from the clipboard:
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
Image pastedImage = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
// how to get mime type?
} catch (Exception e) {/*cutted for brevity*/}
}
Now, I know how to get the mime type from a file using apache Tika and I've tried writing the image to disk in order to reuse this technique, but also the ImageIO.write
method requires a format name:
BufferedImage bi = convertImageToBI(img);
File outputfile = File.createTempFile("img_", "_upload");
ImageIO.write(bi, "jpg", outputfile);
To convert an image to a BufferedImage I'm using this method. The only difference is that I'm using TYPE_INT_RGB
instead of TYPE_INT_ARGB
.
How can I get the pasted image's mime type?