使用Chrome headless和C#截取屏幕截图

时间:2017-10-16 18:01:00

标签: c# asp.net-mvc google-chrome google-chrome-headless

我尝试使用来自ASP.Net MVC应用程序的无头网络截图,这里是代码:

public string TakeScreenshot(ScreenshotRequest request)
{
    var pathToScreenshotFile = Path.Combine(Path.GetTempPath(), $"{request.FileName}.png");
    var arguments = $@" --headless --hide-scrollbars --disable-gpu --screenshot=""{pathToScreenshotFile}"" --window-size={request.Width},{request.Height} https://google.com";

    var psi = new ProcessStartInfo(pathToBrowser) { UseShellExecute = false, Verb = "runas" };
    using (Process process = Process.Start(psi))
    {
        Thread.Sleep(1000);
        var image = string.Empty;
        var executionCount = 0;
        while(image == string.Empty && executionCount < 5)
        {
            if (File.Exists(pathToScreenshotFile))
            {
                image = Convert.ToBase64String(File.ReadAllBytes(pathToScreenshotFile));
            }
            else
            {
                Thread.Sleep(1000);
            }
        }
        return image;
    }
}

pathToBrowser变量指向chrome可执行文件:C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

由于某种原因,文件没有被创建,但如果我打开一个终端并运行以下命令就可以了:

E:\sources\chromium\bin\chrome.exe" --headless --hide-scrollbars --disable-gpu --screenshot="C:\Windows\TEMP\5353e1ab-783c-442a-8d72-54d030529e68a.png" --window-size=1920,874 https://google.com

有什么想法吗?我认为它需要作为管理员运行,因此&#34; runas&#34;,但这没有帮助。

修改

我认为它与权限相关,因为当我从控制台应用程序运行它时,相同的代码可以正常工作。现在我有一个包含Chrome的文件夹,每个人都有完全控制权。我不知道我还缺少什么。

1 个答案:

答案 0 :(得分:1)

对我来说很有用。我必须在arguments中添加ProcessStartInfo

private void Form1_Load(object sender, EventArgs e)
{
    var output = TakeScreenshot(@"C:\Windows\TEMP\5353e1ab-783c-442a-8d72-54d030529e68a.png");
}
public string TakeScreenshot(string request)
{
    var pathToBrowser = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
    var pathToScreenshotFile = Path.Combine(Path.GetTempPath(), $"{request}.png");
    var arguments = $@" --headless --hide-scrollbars --disable-gpu --screenshot=""{pathToScreenshotFile}"" --window-size={1920},{874} https://google.com";

    var psi = new ProcessStartInfo(pathToBrowser,arguments) { UseShellExecute = false, Verb = "runas" };
    using (Process process = Process.Start(psi))
    {
        Thread.Sleep(1000);
        var image = string.Empty;
        var executionCount = 0;
        while (image == string.Empty && executionCount < 5)
        {
            if (File.Exists(pathToScreenshotFile))
            {
                image = Convert.ToBase64String(File.ReadAllBytes(pathToScreenshotFile));
            }
            else
            {
                Thread.Sleep(1000);
            }
        }
        return image;
    }
}