将存储为 XML 字符串的 SVG 图像作为 image/svg+xml MIME 类型复制到 Windows 剪贴板

Copy SVG image stored as XML string to Windows clipboard as image/svg+xml MIME type

我将 SVG 图像存储为 .net XML string。如果我将该字符串写入文件,我可以毫不费力地将它加载到 SVG 编辑器中,所以我知道它的内容是好的。但我想做的是将它作为 image/svg+xml MIME 类型放在 Windows 剪贴板中。我尝试了以下方法:

string svg = GetSvg();
byte[] bytes = Encoding.UTF8.GetBytes(svg);

Clipboard.SetData("image/svg+xml", svg); // idea 1
Clipboard.SetData("image/svg+xml", bytes); // idea 2

根据我的剪贴板查看器工具,这两种技术产生(几乎)相同的结果——XML 文本如预期的那样存在于 image/svg+xml 下,但它是以 svgbytes:

中绝对不存在的 43 个字节为前缀

根据我将文本写成字符串还是字节数组,这些字节略有不同,所以我怀疑它们是对数据格式的某种描述。但是,我没有任何 SVG 编辑器会接受粘贴结果。我还需要做些什么吗?

那些额外的字节看起来非常像序列化 header,所以我四处寻找并最终在 Clipboard class 的 MSDN 文档中找到了这个 note (加粗我的):

An object must be serializable for it to be put on the Clipboard. If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception. See System.Runtime.Serialization for more information on serialization. If your target application requires a very specific data format, the headers added to the data in the serialization process may prevent the application from recognizing your data. To preserve your data format, add your data as a Byte array to a MemoryStream and pass the MemoryStream to the SetData method.

这表明了一个明显的行动方案:

string svg = GetSvg();
byte[] bytes = Encoding.UTF8.GetBytes(svg);
MemorySteam stream = new MemoryStream(bytes);
Clipboard.SetData("image/svg+xml", stream);

成功了!此外,我可以确认 DataObject.SetData() 也将接受 MemoryStream,以防您希望同时以 svg 和位图形式将图像推送到剪贴板。