mirror of
https://github.com/cefsharp/CefSharp.git
synced 2026-12-05 19:54:53 +00:00
OffScreen - Add CaptureScreenshotAsync, GetContentSizeAsync and ResizeAsync
- Simply taking full page screenshots - Added new methods - CaptureScreenshotAsync uses Devtools protocol and allows for specifying image format and quality (if jpg) Cannot use clip param as https://bitbucket.org/chromiumembedded/cef/issues/3103/offscreen-capture-screenshot-with-devtools
This commit is contained in:
@@ -4,9 +4,9 @@
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using CefSharp.DevTools.Page;
|
||||
|
||||
namespace CefSharp.OffScreen.Example
|
||||
{
|
||||
@@ -14,6 +14,8 @@ namespace CefSharp.OffScreen.Example
|
||||
{
|
||||
private const string TestUrlOne = "https://www.google.com/";
|
||||
private const string TestUrlTwo = "https://github.com/";
|
||||
private const string TestUrlThree = "https://www.google.com/doodles";
|
||||
private const string TestUrlFour = "https://microsoft.com/";
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
@@ -22,7 +24,7 @@ namespace CefSharp.OffScreen.Example
|
||||
Console.WriteLine();
|
||||
|
||||
//Console app doesn't have a message loop which we need as Cef.Initialize/Cef.Shutdown must be called on the same
|
||||
//thread. We use a super simple implementation from
|
||||
//thread. We use a super simple SynchronizationContext implementation from
|
||||
//https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/
|
||||
//Continuations will happen on the main thread
|
||||
//The Nito.AsyncEx.Context Nuget package has a more advanced implementation
|
||||
@@ -39,14 +41,16 @@ namespace CefSharp.OffScreen.Example
|
||||
return;
|
||||
}
|
||||
|
||||
var t1 = MainAsync(TestUrlOne, "cache\\path1", 1.0);
|
||||
var t1 = MainAsync(TestUrlOne, TestUrlTwo, "cache\\path1", 1.0);
|
||||
//Demo showing Zoom Level of 2.0
|
||||
//Using seperate request contexts allows the urls from the same domain to have independent zoom levels
|
||||
//otherwise they would be the same - default behaviour of Chromium
|
||||
var t2 = MainAsync(TestUrlTwo, "cache\\path2", 2.0);
|
||||
var t2 = MainAsync(TestUrlThree, TestUrlFour, "cache\\path2", 2.0);
|
||||
|
||||
await Task.WhenAll(t1, t2);
|
||||
|
||||
Console.WriteLine("Image viewer launched. Press any key to exit.");
|
||||
|
||||
// Wait for user input
|
||||
Console.ReadKey();
|
||||
|
||||
@@ -64,7 +68,7 @@ namespace CefSharp.OffScreen.Example
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static async Task MainAsync(string url, string cachePath, double zoomLevel)
|
||||
private static async Task MainAsync(string url, string secondUrl, string cachePath, double zoomLevel)
|
||||
{
|
||||
var browserSettings = new BrowserSettings
|
||||
{
|
||||
@@ -125,54 +129,74 @@ namespace CefSharp.OffScreen.Example
|
||||
////Give the browser a little time to finish drawing our SendKeyEvent input
|
||||
//await Task.Delay(100);
|
||||
|
||||
var contentSize = await browser.GetContentSizeAsync();
|
||||
|
||||
var viewport = new Viewport
|
||||
{
|
||||
Height = contentSize.Height,
|
||||
Width = contentSize.Width,
|
||||
Scale = 1.0
|
||||
};
|
||||
|
||||
// Wait for the screenshot to be taken,
|
||||
// if one exists ignore it, wait for a new one to make sure we have the most up to date
|
||||
var bitmap = await browser.ScreenshotAsync(true);
|
||||
var bitmap = await browser.CaptureScreenshotAsync(viewport:viewport);
|
||||
|
||||
DisplayBitmap(bitmap);
|
||||
// Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png)
|
||||
var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png");
|
||||
|
||||
//await browser.LoadUrlAsync("http://github.com");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
|
||||
|
||||
File.WriteAllBytes(screenshotPath, bitmap);
|
||||
|
||||
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
|
||||
|
||||
// Tell Windows to launch the saved image.
|
||||
Process.Start(new ProcessStartInfo(screenshotPath)
|
||||
{
|
||||
// UseShellExecute is false by default on .NET Core.
|
||||
UseShellExecute = true
|
||||
});
|
||||
|
||||
await browser.LoadUrlAsync(secondUrl);
|
||||
|
||||
// Gets a warpper around the CefBrowserHost instance
|
||||
// You can perform a lot of low level browser operations using this interface
|
||||
//var cefbrowserHost = browser.GetBrowserHost();
|
||||
var cefbrowserHost = browser.GetBrowserHost();
|
||||
|
||||
//You can call Invalidate to redraw/refresh the image
|
||||
//cefbrowserHost.Invalidate(PaintElementType.View);
|
||||
cefbrowserHost.Invalidate(PaintElementType.View);
|
||||
|
||||
// Wait for the screenshot to be taken.
|
||||
//bitmap = await browser.ScreenshotAsync(true);
|
||||
contentSize = await browser.GetContentSizeAsync();
|
||||
|
||||
//DisplayBitmap(bitmap);
|
||||
viewport = new Viewport
|
||||
{
|
||||
Height = contentSize.Height,
|
||||
Width = contentSize.Width,
|
||||
Scale = 1.0
|
||||
};
|
||||
|
||||
// Wait for the screenshot to be taken,
|
||||
// if one exists ignore it, wait for a new one to make sure we have the most up to date
|
||||
bitmap = await browser.CaptureScreenshotAsync(viewport: viewport);
|
||||
|
||||
screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png");
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
|
||||
|
||||
File.WriteAllBytes(screenshotPath, bitmap);
|
||||
|
||||
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
|
||||
|
||||
// Tell Windows to launch the saved image.
|
||||
Process.Start(new ProcessStartInfo(screenshotPath)
|
||||
{
|
||||
// UseShellExecute is false by default on .NET Core.
|
||||
UseShellExecute = true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static void DisplayBitmap(Bitmap bitmap)
|
||||
{
|
||||
// Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png)
|
||||
var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png");
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
|
||||
|
||||
// Save the Bitmap to the path.
|
||||
// The image type is auto-detected via the ".png" extension.
|
||||
bitmap.Save(screenshotPath);
|
||||
|
||||
// We no longer need the Bitmap.
|
||||
// Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications.
|
||||
bitmap.Dispose();
|
||||
|
||||
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
|
||||
|
||||
// Tell Windows to launch the saved image.
|
||||
Process.Start(new ProcessStartInfo(screenshotPath)
|
||||
{
|
||||
// UseShellExecute is false by default on .NET Core.
|
||||
UseShellExecute = true
|
||||
});
|
||||
|
||||
Console.WriteLine("Image viewer launched. Press any key to exit.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CefSharp.DevTools.Page;
|
||||
using CefSharp.Enums;
|
||||
using CefSharp.Internals;
|
||||
using CefSharp.Structs;
|
||||
@@ -45,6 +46,7 @@ namespace CefSharp.OffScreen
|
||||
/// uderlying Chromium Embedded Framework (CEF) browser has been created.
|
||||
/// </summary>
|
||||
private Action<IBrowser> onAfterBrowserCreatedDelegate;
|
||||
private float deviceScaleFactor = 1.0f;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this instance is disposed.
|
||||
@@ -402,6 +404,23 @@ namespace CefSharp.OffScreen
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Device scale factor. Specifies the ratio between physical and logical pixels.
|
||||
/// </summary>
|
||||
public float DeviceScaleFactor
|
||||
{
|
||||
get { return deviceScaleFactor; }
|
||||
set
|
||||
{
|
||||
deviceScaleFactor = value;
|
||||
|
||||
if (IsBrowserInitialized)
|
||||
{
|
||||
browser.GetHost().NotifyScreenInfoChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Immediately returns a copy of the last rendering from Chrome,
|
||||
/// or null if no rendering has occurred yet.
|
||||
@@ -467,8 +486,11 @@ namespace CefSharp.OffScreen
|
||||
/// <param name="ignoreExistingScreenshot">Ignore existing bitmap (if any) and return the next available bitmap</param>
|
||||
/// <param name="blend">Choose which bitmap to retrieve, choose <see cref="PopupBlending.Blend"/> for a merged bitmap.</param>
|
||||
/// <returns>Task<Bitmap>.</returns>
|
||||
[Obsolete("Use CaptureScreenshotAsync instead.")]
|
||||
public Task<Bitmap> ScreenshotAsync(bool ignoreExistingScreenshot = false, PopupBlending blend = PopupBlending.Main)
|
||||
{
|
||||
ThrowExceptionIfDisposed();
|
||||
|
||||
// Try our luck and see if there is already a screenshot, to save us creating a new thread for nothing.
|
||||
var screenshot = ScreenshotOrNull(blend);
|
||||
|
||||
@@ -505,6 +527,99 @@ namespace CefSharp.OffScreen
|
||||
return completionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Capture page screenshot.
|
||||
/// </summary>
|
||||
/// <param name="format">Image compression format (defaults to png).</param>
|
||||
/// <param name="quality">Compression quality from range [0..100] (jpeg only).</param>
|
||||
/// <param name="viewport">view port to capture, if not null the browser will be resized to match the width/height.</param>
|
||||
/// <returns>A task that can be awaited to obtain the screenshot as a byte[].</returns>
|
||||
public async Task<byte[]> CaptureScreenshotAsync(CaptureScreenshotFormat? format = null, int? quality = null, Viewport viewport = null)
|
||||
{
|
||||
ThrowExceptionIfDisposed();
|
||||
ThrowExceptionIfBrowserNotInitialized();
|
||||
|
||||
using (var devToolsClient = browser.GetDevToolsClient())
|
||||
{
|
||||
if(viewport != null)
|
||||
{
|
||||
await ResizeAsync((int)viewport.Width, (int)viewport.Height, (float)viewport.Scale).ConfigureAwait(continueOnCapturedContext:false);
|
||||
}
|
||||
|
||||
//https://bitbucket.org/chromiumembedded/cef/issues/3103/offscreen-capture-screenshot-with-devtools
|
||||
//CEF OSR mode doesn't set the size internally when CaptureScreenShot is called with a clip param specified, so
|
||||
//we must manually resize our view.
|
||||
var response = await devToolsClient.Page.CaptureScreenshotAsync(format, quality, fromSurface:true).ConfigureAwait(continueOnCapturedContext: false);
|
||||
|
||||
return response.Data;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resize the browser
|
||||
/// </summary>
|
||||
/// <param name="width">width</param>
|
||||
/// <param name="height">height</param>
|
||||
/// <param name="deviceScaleFactor">device scale factor</param>
|
||||
/// <returns>A task that can be awaited and will resolve when the desired size is achieved.</returns>
|
||||
/// <remarks>
|
||||
/// The current implementation is fairly symplistic, it simply resizes the browser
|
||||
/// and resolves the task when the browser starts painting at the desired size.
|
||||
/// </remarks>
|
||||
public Task ResizeAsync(int width, int height, float? deviceScaleFactor = null)
|
||||
{
|
||||
ThrowExceptionIfDisposed();
|
||||
ThrowExceptionIfBrowserNotInitialized();
|
||||
|
||||
if(size.Width == width && size.Height == height && deviceScaleFactor == null)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
EventHandler<OnPaintEventArgs> handler = null;
|
||||
|
||||
handler = (s, e) =>
|
||||
{
|
||||
if (e.Width == width && e.Height == height)
|
||||
{
|
||||
AfterPaint -= handler;
|
||||
|
||||
tcs.TrySetResultAsync(true);
|
||||
}
|
||||
};
|
||||
|
||||
AfterPaint += handler;
|
||||
|
||||
//Only set the value if not null otherwise
|
||||
//a call to NotifyScreenInfoChanged will be made.
|
||||
if (deviceScaleFactor.HasValue)
|
||||
{
|
||||
DeviceScaleFactor = deviceScaleFactor.Value;
|
||||
}
|
||||
Size = new Size(width, height);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Size of scrollable area in CSS pixels
|
||||
/// </summary>
|
||||
/// <returns>A task that can be awaited to get the size of the scrollable area in CSS pixels.</returns>
|
||||
public async Task<DevTools.DOM.Rect> GetContentSizeAsync()
|
||||
{
|
||||
ThrowExceptionIfDisposed();
|
||||
ThrowExceptionIfBrowserNotInitialized();
|
||||
|
||||
using (var devToolsClient = browser.GetDevToolsClient())
|
||||
{
|
||||
//Get the content size
|
||||
var layoutMetricsResponse = await devToolsClient.Page.GetLayoutMetricsAsync().ConfigureAwait(continueOnCapturedContext:false);
|
||||
|
||||
return layoutMetricsResponse.CssContentSize;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Load(string url)
|
||||
{
|
||||
|
||||
@@ -98,7 +98,7 @@ namespace CefSharp.OffScreen
|
||||
/// <returns>Return null if no screenInfo structure is provided.</returns>
|
||||
public virtual ScreenInfo? GetScreenInfo()
|
||||
{
|
||||
var screenInfo = new ScreenInfo { DeviceScaleFactor = 1.0F };
|
||||
var screenInfo = new ScreenInfo { DeviceScaleFactor = browser.DeviceScaleFactor };
|
||||
|
||||
return screenInfo;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user