gpt4 book ai didi

java - 在Java中查找剪贴板图像的格式

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:11 24 4
gpt4 key购买 nike

我正在使用这个从剪贴板获取图像:

if(Toolkit.getDefaultToolkit().getSystemClipboard().isDataFlavorAvailable(DataFlavor.imageFlavor)){
ImageIcon IMG = new ImageIcon((BufferedImage) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor));
}

现在我想使用ImageIO.write将这个图像保存在磁盘中;
如何找到要在 ImageIO.write 中用作 formatName 的图像格式(JPG、PNG、GIF 等)?

谢谢

最佳答案

通过

检查时剪贴板内容的mime类型
.isDataFlavorAvailable(DataFlavor.imageFlavor)

image/x-java-image (但是 OS vendors do not need to follow MIME types for clipboards )。

我发现了两种从剪贴板获取图像并将其写入文件的方法:

  1. 使用这篇博文中的辅助方法:The nightmares of getting images from the Mac OS X clipboard using Java .

    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard()

    ImageIcon IMG = new ImageIcon((BufferedImage)
    clip.getData(DataFlavor.imageFlavor));
    BufferedImage bImage = getBufferedImage(IMG.getImage());
    ImageIO.write(bImage, "png", new File("/tmp/test.png"));

    getBufferedImage 方法如下所示:

    public static BufferedImage getBufferedImage(Image img) {
    if (img == null) {
    return null;
    }
    int w = img.getWidth(null);
    int h = img.getHeight(null);
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage bufimg = new BufferedImage(w, h,
    BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bufimg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0, w, h, null);
    g2.dispose();
    return bufimg;
    }
  2. 通过可转让。请注意,这在 OS X 上运行但会生成正确大小的空图像:

    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard()
    Transferable content =
    clip.getContents(null);
    BufferedImage img = (BufferedImage) content.getTransferData(
    DataFlavor.imageFlavor);
    ImageIO.write(img, "png", new File("/tmp/test.png"));

关于java - 在Java中查找剪贴板图像的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14129221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com