我有一个桌面java应用程序,它从用户剪贴板获取图像(“粘贴”操作),我需要在进一步处理之前检查它们的mime类型(只允许jpg,png和gif )。
我使用以下代码从剪贴板获取图像:
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*/}
}现在,我知道how to get the mime type from a file using apache Tika和我已经尝试过将图像写入磁盘以重用此技术,但ImageIO.write方法还需要一个格式名称:
BufferedImage bi = convertImageToBI(img);
File outputfile = File.createTempFile("img_", "_upload");
ImageIO.write(bi, "jpg", outputfile);为了将图像转换为BufferedImage,我使用了this method。唯一的区别是我使用的是TYPE_INT_RGB而不是TYPE_INT_ARGB。
如何获取粘贴图像的mime类型?
发布于 2021-11-18 13:43:46
我尝试了一种疯狂的方法来检查它是JPG/GIF还是PNG。当有透明度时,我使用PNG,除此之外我总是使用JPG,这也被证明可以与GIF一起工作,只是GIF失去了它的动画效果
protected BufferedImage img;
protected void loadImage() {
try {
// Well we read the temp file first, I test it using local file
File f = new File(loc);
// Read the file as Image
this.img = ImageIO.read(f);
} catch(Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
this.revalidate();
this.repaint();
}
public byte[] toBlob() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// Check if this image contains transparency? If no then write as JPG
if (this.img.getTransparency() == java.awt.Transparency.OPAQUE) {
ImageIO.write((BufferedImage)this.img, "jpg", baos);
} else { // If it does contain transparency then write as PNG
ImageIO.write((BufferedImage)this.img, "png", baos);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
byte[] data = baos.toByteArray();
return data;
}
public void saveImageToBlob(String location) {
try {
File f = new File(location);
FileOutputStream o = new FileOutputStream(f);
byte[] d = this.toBlob();
o.write(d, 0, d.length);
o.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}https://stackoverflow.com/questions/42230820
复制相似问题