.net - 接收从网页拖动到 WPF 窗口的图像

标签 .net wpf winforms drag-and-drop bitmap

我希望我的 WPF 应用程序成为放置目标,并且我希望能够从任何网页拖动图像。

当从网页中拖动图像时,它显然是“DragImageBits”格式,可以将其反序列化为 ShDragImage . (有关我如何定义它,请参阅问题的底部)

如何将其转换为 WPF 图像?

这是我目前的尝试。 (如果有人知道进行反序列化的正确方法,我全神贯注)

   private void UserControl_Drop(object sender, System.Windows.DragEventArgs e)
    {

            string[] formats = data.GetFormats();

            // DragImageBits
            if (formats.Contains("DragImageBits"))
            {
            MemoryStream imageStream = data.GetData("DragImageBits") as MemoryStream;

            // Now I'm deserializing this, the only way I know how
            imageStream.Seek(0, SeekOrigin.Begin);
            BinaryReader br = new BinaryReader(imageStream);

            ShDragImage shDragImage;
            shDragImage.sizeDragImage.cx = br.ReadInt32();
            shDragImage.sizeDragImage.cy = br.ReadInt32();
            shDragImage.ptOffset.x = br.ReadInt32();
            shDragImage.ptOffset.y = br.ReadInt32();
            shDragImage.hbmpDragImage = new IntPtr(br.ReadInt32());
            shDragImage.crColorKey = br.ReadInt32();


            var systemDrawingBitmap = System.Drawing.Bitmap.FromHbitmap(shDragImage.hbmpDragImage);

在这一点上,我得到了一个 System.Runtime.InteropServices.ExternalException 类型的异常。 , 消息只是 Generic GDI+ error .

有谁知道我应该做什么?

这是支持的类定义。我从 this blog entry 复制它们.
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct Win32Point
    {
        public int x;
        public int y;
    }

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct Win32Size
    {
        public int cx;
        public int cy;
    }

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct ShDragImage
    {
        public Win32Size sizeDragImage;
        public Win32Point ptOffset;
        public IntPtr hbmpDragImage;
        public int crColorKey;
    }

最佳答案

这是我学到的:
"DragImageBits"由 windows shell 提供,仅用于拖动光标,而不用于最终数据。 shell 通过调整大小和透明度将图像转换为适当的拖动光标。
例如,如果您拖动此图像:
Fully Opaque Image
SHDRAGIMAGE 将呈现如下:
enter image description here
如果你真的想从 SHDRAGIMAGE 中提取图像,这里是代码。 (部分摘自 this answer )

        MemoryStream imageStream = data.GetData("DragImageBits") as MemoryStream;
        imageStream.Seek(0, SeekOrigin.Begin);
        BinaryReader br = new BinaryReader(imageStream);
        ShDragImage shDragImage;
        shDragImage.sizeDragImage.cx = br.ReadInt32();
        shDragImage.sizeDragImage.cy = br.ReadInt32();
        shDragImage.ptOffset.x = br.ReadInt32();
        shDragImage.ptOffset.y = br.ReadInt32();
        shDragImage.hbmpDragImage = new IntPtr(br.ReadInt32()); // I do not know what this is for!
        shDragImage.crColorKey = br.ReadInt32();
        int stride = shDragImage.sizeDragImage.cx * 4;
        var imageData = new byte[stride * shDragImage.sizeDragImage.cy];
        // We must read the image data as a loop, so it's in a flipped format
        for (int i = (shDragImage.sizeDragImage.cy - 1) * stride; i >= 0; i -= stride) 
        {
            br.Read(imageData, i, stride);
        }
        var bitmapSource = BitmapSource.Create(shDragImage.sizeDragImage.cx, shDragImage.sizeDragImage.cy,
                                                    96, 96,
                                                    PixelFormats.Bgra32,
                                                    null,
                                                    imageData,
                                                    stride);
如果您想将 DragImageBits 用于其预期目的(作为拖动图像),请参阅 Shell Style Drag and Drop in .NET (WPF and WinForms) (存档 here)一个简单的、可下载的例子。

因此,“DragImageBits”几乎分散了实际问题的注意力,即接受从网页拖动的图像。
从网页中拖动图像会变得很复杂,因为 Firefox、Chrome 和 IE9 都为您提供了一组不同的格式。此外,您希望同时处理图像和图像超链接,它们的处理方式又有所不同。
Google 和 Firefox 提供了“text/html”格式,它为您提供单个 HTML 元素作为图像。 Google 将其作为 ASCII 字符串提供给您,而 Firefox 将其作为 unicode 字符串提供给您。所以这是我编写的代码来处理它:
     System.Windows.IDataObject data = e.Data;
        string[] formats = data.GetFormats();


        if (formats.Contains("text/html"))
        {

            var obj = data.GetData("text/html");
            string html = string.Empty;
            if (obj is string)
            {
                html = (string)obj;
            }
            else if (obj is MemoryStream)
            {
                MemoryStream ms = (MemoryStream)obj;
                byte[] buffer = new byte[ms.Length];
                ms.Read(buffer, 0, (int)ms.Length);
                if (buffer[1] == (byte)0)  // Detecting unicode
                {
                    html = System.Text.Encoding.Unicode.GetString(buffer);
                }
                else
                {
                    html = System.Text.Encoding.ASCII.GetString(buffer);
                }
            }
            // Using a regex to parse HTML, but JUST FOR THIS EXAMPLE :-)
            var match = new Regex(@"<img[^/]src=""([^""]*)""").Match(html);
            if (match.Success)
            {
                Uri uri = new Uri(match.Groups[1].Value);
                SetImageFromUri(uri);
            }
        }
在这种情况下,正则表达式将处理直接图像和图像超链接。
还有我的 SetImageFromUri功能:
    private void SetImageFromUri(Uri uri)
    {
        string fileName = System.IO.Path.GetTempFileName();
        using (WebClient webClient = new WebClient())
        {
            webClient.DownloadFile(uri, fileName);
        }
        using (FileStream fs = File.OpenRead(fileName))
        {
            byte[] imageData = new byte[fs.Length];
            fs.Read(imageData, 0, (int)fs.Length);
            this.ImageBinary = imageData;
        }
        File.Delete(fileName);
    }
对于 IE9,您可以处理“FileDrop”格式。这在 IE9 中运行良好。 Chrome 不支持它。 Firefox 确实支持它,但会将图像转换为位图并将透明像素转换为黑色。因此,如果“text.html”格式不可用,您应该只处理“FileDrop”格式。
    else if (formats.Contains("FileDrop"))
    {
        var filePaths = (string[])data.GetData("FileDrop");
        using (var fileStream = File.OpenRead(filePaths[0]))
        {
            var buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, (int)fileStream.Length);
            this.ImageBinary = buffer;
        }
    }
如果从 IE9 中拖动图像超链接,则不提供“FileDrop”格式。我还没有弄清楚如何将图像从 IE9 中的图像超链接拖到我的图像控件上。

**额外信息**
如果您正在使用此示例,但仍需要将此二进制数据转换为图像,这里有一个有用的代码片段:
                BitmapImage sourceImage = new BitmapImage();
                using (MemoryStream ms = new MemoryStream(imageBinary))
                {
                    sourceImage.BeginInit();
                    sourceImage.CacheOption = BitmapCacheOption.OnLoad;
                    sourceImage.StreamSource = ms;
                    sourceImage.EndInit();
                }

关于.net - 接收从网页拖动到 WPF 窗口的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8442085/

相关文章:

.net - 是否可以防止 WPF 控件重绘?

c# - 国际化 HelloWorld 程序 .NET

c# - 如何在Control上绘图以使绘图不消失?

javascript - 二月份的表单验证

c# - 更新数据库失败,因为它是只读的

WPF、应用程序设计建议和数据库并发

c# - WPF 和装饰器

c# - 为什么我的工具提示不显示它的提示?

.net - 如何调试 Windows 窗体设计器崩溃?

.net - 全局化现有的Windows Forms应用程序?