首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从image对象获取图像mime类型

从image对象获取图像mime类型
EN

Stack Overflow用户
提问于 2017-02-15 00:03:39
回答 1查看 1.1K关注 0票数 1

我有一个桌面java应用程序,它从用户剪贴板获取图像(“粘贴”操作),我需要在进一步处理之前检查它们的mime类型(只允许jpg,png和gif )。

我使用以下代码从剪贴板获取图像:

代码语言:javascript
复制
  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方法还需要一个格式名称:

代码语言:javascript
复制
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类型?

EN

回答 1

Stack Overflow用户

发布于 2021-11-18 13:43:46

我尝试了一种疯狂的方法来检查它是JPG/GIF还是PNG。当有透明度时,我使用PNG,除此之外我总是使用JPG,这也被证明可以与GIF一起工作,只是GIF失去了它的动画效果

代码语言:javascript
复制
    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());
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42230820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档