使用phantomjs和asp.net web api截取网页截图

时间:2014-04-28 13:49:30

标签: c# asp.net asp.net-web-api phantomjs

我试图截取网址的屏幕截图,并将截图保存在我的服务器上。我正在使用phantomjs来截取屏幕截图。 我在网上找到了一些示例代码,但它在我的应用程序中无法运行。

似乎陷入了DoWhile方法。

然而,当我从cmd.exe运行phantomjs时,它工作正常。

phantomjs rasterize.js http://www.google.com google.png

在我的项目中,我有一个名为" Phantomjs"的文件夹,其中包含phantomjs.exe和rasterize.js脚本。

你有什么指示我做错了吗?

private static void GrabUrl(String url)
        {
            string serverPath = HttpContext.Current.Server.MapPath("~/Phantomjs/");
            string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".png";

            new Thread(new ParameterizedThreadStart(x =>
            {
                ExecuteCommand("cd " + serverPath + @" & phantomjs rasterize.js " + url + " " + filename + @" ""A4""");
            })).Start();

            var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Phantomjs/"), filename);

            var stream = new MemoryStream();
            byte[] bytes = DoWhile(filePath);


        }

private void ExecuteCommand(string Command)
    {
     try
     {
      ProcessStartInfo ProcessInfo;
      Process Process;

      ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
      ProcessInfo.CreateNoWindow = true;
      ProcessInfo.UseShellExecute = false;

      Process = Process.Start(ProcessInfo);
     }
     catch { }
    }


    private byte[] DoWhile(string filePath)
    {
     byte[] bytes = new byte[0];
     bool fail = true;

     while (fail)
     {
      try
      {
       using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
       {
           bytes = new byte[file.Length];
           file.Read(bytes, 0, (int)file.Length);
       }

       fail = false;
      }
      catch
      {
        Thread.Sleep(1000);
      }
     }

     System.IO.File.Delete(filePath);
     return bytes;
    }

在Execute命令中删除try / catch块什么也没做。我得到一个例外:

Exception:Thrown: "Could not find file 'C:\ ~\Web API\Phantomjs\28042014_042756.png'." (System.IO.FileNotFoundException)
A System.IO.FileNotFoundException was thrown: "Could not find file 'C:\~\Web API\Phantomjs\28042014_042756.png'."
Time: 28-Apr-14 16:28:00
Thread:Worker Thread[2068]

0 个答案:

没有答案