[英]Taking a screenshot using Chrome headless and C#
我正在嘗試使用來自 ASP.Net MVC 應用程序的 Chrome 無頭截圖,這是代碼:
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
有任何想法嗎? 我認為它需要以管理員身份運行,因此是“runas”,但這沒有幫助。
編輯:
我認為這與權限有關,因為當我從控制台應用程序運行它時,相同的代碼可以工作。 現在我有一個文件夾,其中包含對所有人具有完全控制權的 Chrome。 我不知道我還缺少什么。
它對我很有用。 我確實必須在ProcessStartInfo
包含arguments
。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.