将图像设置到剪贴板 - Java
我正在使用 java 编写一个程序,通过套接字发送剪贴板内容;我设法让它与字符串一起工作,但在处理图像时遇到了一些麻烦。代码如下:
//get Image
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Image imageContents = (Image)clipboard.getData(DataFlavor.imageFlavor);
ImageIcon image = new ImageIcon(imageContents);
//sent over sockets
//set Image
String mime = DataFlavor.imageFlavor.getMimeType();
DataHandler contents = new DataHandler(image,mime);
//set clipboard
clipboard.setContents(contents, null);
setContents 之后剪贴板为空;任何想法为什么以及如何解决它?
I'm making a program using java that sends the clipboard contents over sockets; I managed to make it work with strings but I'm having some troubles with images. Here is the code:
//get Image
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Image imageContents = (Image)clipboard.getData(DataFlavor.imageFlavor);
ImageIcon image = new ImageIcon(imageContents);
//sent over sockets
//set Image
String mime = DataFlavor.imageFlavor.getMimeType();
DataHandler contents = new DataHandler(image,mime);
//set clipboard
clipboard.setContents(contents, null);
After setContents the clipboard is empty; Any ideas why, and how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我用来从剪贴板写入/读取图像的一些代码。从未尝试过使用套接字,所以我不确定它是否有帮助:
Here is some code I've used to write/read an Image from the clipboard. Never tried it with sockets so I'm not sure it will help:
DataHandler 将不会按照您规定的方式运行,因为根据 API:
我的理解是,除非您使用其
setDataContentHandlerFactory
方法并实现其中所有必需的接口,否则 DataHandler 本质上只会返回 null。这可能是 DataHandler 无法按您预期运行的原因。尽管它实现了Transferable
接口,但它的实现方式并不能充分满足您的特定需求。此功能将由 DataContentHandler 提供,其实现将由您决定。
按照之前的建议直接实现 Transferable 类似乎不那么繁琐。
DataHandler will not function in the way you've prescribed because according to the API:
I understand this to mean that unless you use its
setDataContentHandlerFactory
method and implement all required interfaces therein, essentially, DataHandler will simply return null. This is likely the reason why DataHandler does not function as you expect. Even though it implements theTransferable
interface, it does not implement it in a way that functions adequately for your particular needs.This functionality would be given by a
DataContentHandler
whose implementation would be left up to you.It seems less tedious to directly implement the Transferable class as suggested prior.