Awesomium如何在不重新下载的情况下保存加载的图像

时间:2015-07-27 13:50:34

标签: c# .net winforms visual-studio-2013 awesomium

如何将 Awesomium 浏览器中加载的图像复制或保存到本地磁盘而不重新下载?

有一种下载图像的方法:
http://docs.awesomium.net/html/M_Awesomium_Windows_Controls_WebControl_SaveImageAt.htm

但它有两个问题:

  1. 重新下载图片。
  2. 它会显示一个保存图像的弹出窗口,我不想要它。
  3. 此外,javascript中的每一种方式都会重新下载目标图片! 解决方案是什么?
    我们如何从缓存文件夹中获取下载的图像?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

    /// <summary>
    /// Returns Base64 string of image content. Without redownloading image. If it is not on the same domain, WebSecurity must be set to false.
    /// </summary>
    /// <param name="getElementQuery">
    /// <para>Any Javascript query to get an element.</para>
    /// <para>Examples:</para>
    /// <para>"document.getElementById('id')"</para>
    /// <para>"document.getElementsByClassName('name')[0]"</para>
    /// <para>"document.evaluate(\"//a[contains(@href, 'something')]\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue" (XPath)</para>
    /// </param>
    /// <param name="leaveOnlyBase64Data">if true, removes "data:image/type;base64," from the beginning of the string</param>
    /// <returns>Base64 string or empty string in case of error</returns>
    public static string JsGetImgBase64String(string getElementQuery, bool leaveOnlyBase64Data = true)
    {
        string data = webView.ExecuteJavascriptWithResult(@"
                                        function getImgBase64String(img)
                                        {
                                            var cnv = document.createElement('CANVAS');
                                            var ctx = cnv.getContext('2d');
                                            ctx.drawImage(img, 0, 0);
                                            return cnv.toDataURL();
                                        }
                            " + String.Format("getImgBase64String({0});", getElementQuery));

        if (data == "undefined")
            return string.Empty;

        if (leaveOnlyBase64Data && data.Contains(","))
        {
            data = data.Substring(data.IndexOf(",") + 1);
        }

        return data;
    }

用法:

 string imgBase64 = JsGetImgBase64String("document.getElementById('imageId')");
 byte[] imgBytes = Convert.FromBase64String(imgBase64 );

如果图片不在同一个域中,您可能需要在WebSecurity中将false设置为WebPreferences