-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageSharpRender.cs
More file actions
467 lines (408 loc) · 17.1 KB
/
Copy pathImageSharpRender.cs
File metadata and controls
467 lines (408 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
using FlexRender.Abstractions;
using FlexRender.Configuration;
using FlexRender.ImageSharp.Rendering;
using FlexRender.Parsing.Ast;
using FlexRender.TemplateEngine;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
namespace FlexRender.ImageSharp;
/// <summary>
/// ImageSharp-based implementation of <see cref="IFlexRender"/>.
/// Provides a pure .NET rendering backend with zero native dependencies.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the ImageSharp rendering backend for FlexRender. It uses
/// SixLabors.ImageSharp for cross-platform 2D graphics rendering without any
/// native library dependencies.
/// </para>
/// <para>
/// Instances are typically created through <see cref="FlexRenderBuilder"/> using the
/// <c>WithImageSharp()</c> extension method:
/// </para>
/// <code>
/// var render = new FlexRenderBuilder()
/// .WithImageSharp()
/// .Build();
/// </code>
/// </remarks>
public sealed class ImageSharpRender : IFlexRender
{
private readonly ImageSharpRenderingEngine _engine;
private readonly ImageSharpFontManager _fontManager;
private readonly IReadOnlyList<IResourceLoader> _resourceLoaders;
private readonly FilterRegistry? _filterRegistry;
private readonly ContentParserRegistry? _contentParserRegistry;
private readonly ResourceLimits _limits;
private readonly FlexRenderOptions _options;
private readonly RenderOptions _defaultRenderOptions;
private int _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="ImageSharpRender"/> class.
/// </summary>
/// <param name="limits">Resource limits for rendering operations.</param>
/// <param name="options">Rendering configuration options.</param>
/// <param name="resourceLoaders">Collection of resource loaders for assets.</param>
/// <param name="builder">ImageSharp-specific configuration.</param>
/// <param name="filterRegistry">Optional filter registry for expression filter evaluation.</param>
/// <param name="contentParserRegistry">Optional content parser registry for custom content type parsing.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="limits"/>, <paramref name="options"/>,
/// <paramref name="resourceLoaders"/>, or <paramref name="builder"/> is null.
/// </exception>
internal ImageSharpRender(
ResourceLimits limits,
FlexRenderOptions options,
IReadOnlyList<IResourceLoader> resourceLoaders,
ImageSharpBuilder builder,
FilterRegistry? filterRegistry = null,
ContentParserRegistry? contentParserRegistry = null)
{
ArgumentNullException.ThrowIfNull(limits);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(resourceLoaders);
ArgumentNullException.ThrowIfNull(builder);
_limits = limits;
_options = options;
_defaultRenderOptions = options.DefaultRenderOptions;
_resourceLoaders = resourceLoaders;
_filterRegistry = filterRegistry;
_contentParserRegistry = contentParserRegistry;
_fontManager = new ImageSharpFontManager();
var textRenderer = new ImageSharpTextRenderer(_fontManager);
_engine = new ImageSharpRenderingEngine(
textRenderer,
_fontManager,
limits,
options.BaseFontSize,
builder.QrProvider,
builder.BarcodeProvider,
options,
resourceLoaders);
}
// ========================================================================
// EXISTING METHODS (unchanged signatures from IFlexRender)
// ========================================================================
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">Thrown when the renderer has been disposed.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="layoutTemplate"/> is null.</exception>
public async Task<byte[]> Render(
Template layoutTemplate,
ObjectValue? data = null,
ImageFormat format = ImageFormat.Png,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(layoutTemplate);
using var stream = new MemoryStream();
await Render(stream, layoutTemplate, data, format, cancellationToken).ConfigureAwait(false);
return stream.ToArray();
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">Thrown when the renderer has been disposed.</exception>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="output"/> or <paramref name="layoutTemplate"/> is null.
/// </exception>
public async Task Render(
Stream output,
Template layoutTemplate,
ObjectValue? data = null,
ImageFormat format = ImageFormat.Png,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(layoutTemplate);
var effectiveData = data ?? new ObjectValue();
switch (format)
{
case ImageFormat.Png:
await RenderToPng(output, layoutTemplate, effectiveData, null, null, cancellationToken).ConfigureAwait(false);
break;
case ImageFormat.Jpeg:
await RenderToJpeg(output, layoutTemplate, effectiveData, null, null, cancellationToken).ConfigureAwait(false);
break;
case ImageFormat.Bmp:
await RenderToBmp(output, layoutTemplate, effectiveData, null, null, cancellationToken).ConfigureAwait(false);
break;
case ImageFormat.Raw:
await RenderToRaw(output, layoutTemplate, effectiveData, null, cancellationToken).ConfigureAwait(false);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, "Unsupported image format.");
}
}
// ========================================================================
// FORMAT-SPECIFIC METHODS
// ========================================================================
// --- PNG ---
/// <inheritdoc />
public async Task<byte[]> RenderToPng(
Template layoutTemplate,
ObjectValue? data = null,
PngOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(layoutTemplate);
using var stream = new MemoryStream();
await RenderToPng(stream, layoutTemplate, data, options, renderOptions, cancellationToken).ConfigureAwait(false);
return stream.ToArray();
}
/// <inheritdoc />
public async Task RenderToPng(
Stream output,
Template layoutTemplate,
ObjectValue? data = null,
PngOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(layoutTemplate);
cancellationToken.ThrowIfCancellationRequested();
var effectiveData = data ?? new ObjectValue();
var (processedTemplate, imageCache) = await PreloadImages(layoutTemplate, effectiveData, cancellationToken)
.ConfigureAwait(false);
try
{
using var image = _engine.RenderToImage(processedTemplate, imageCache);
var encoder = new PngEncoder();
await image.SaveAsync(output, encoder, cancellationToken).ConfigureAwait(false);
}
finally
{
DisposeImageCache(imageCache);
}
}
// --- JPEG ---
/// <inheritdoc />
public async Task<byte[]> RenderToJpeg(
Template layoutTemplate,
ObjectValue? data = null,
JpegOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(layoutTemplate);
using var stream = new MemoryStream();
await RenderToJpeg(stream, layoutTemplate, data, options, renderOptions, cancellationToken).ConfigureAwait(false);
return stream.ToArray();
}
/// <inheritdoc />
public async Task RenderToJpeg(
Stream output,
Template layoutTemplate,
ObjectValue? data = null,
JpegOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(layoutTemplate);
cancellationToken.ThrowIfCancellationRequested();
var effectiveData = data ?? new ObjectValue();
var effectiveOptions = options ?? JpegOptions.Default;
var (processedTemplate, imageCache) = await PreloadImages(layoutTemplate, effectiveData, cancellationToken)
.ConfigureAwait(false);
try
{
using var image = _engine.RenderToImage(processedTemplate, imageCache);
var encoder = new JpegEncoder { Quality = effectiveOptions.Quality };
await image.SaveAsync(output, encoder, cancellationToken).ConfigureAwait(false);
}
finally
{
DisposeImageCache(imageCache);
}
}
// --- BMP ---
/// <inheritdoc />
public async Task<byte[]> RenderToBmp(
Template layoutTemplate,
ObjectValue? data = null,
BmpOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(layoutTemplate);
using var stream = new MemoryStream();
await RenderToBmp(stream, layoutTemplate, data, options, renderOptions, cancellationToken).ConfigureAwait(false);
return stream.ToArray();
}
/// <inheritdoc />
public async Task RenderToBmp(
Stream output,
Template layoutTemplate,
ObjectValue? data = null,
BmpOptions? options = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(layoutTemplate);
cancellationToken.ThrowIfCancellationRequested();
var effectiveData = data ?? new ObjectValue();
var (processedTemplate, imageCache) = await PreloadImages(layoutTemplate, effectiveData, cancellationToken)
.ConfigureAwait(false);
try
{
using var image = _engine.RenderToImage(processedTemplate, imageCache);
var encoder = new BmpEncoder { BitsPerPixel = BmpBitsPerPixel.Pixel32 };
await image.SaveAsync(output, encoder, cancellationToken).ConfigureAwait(false);
}
finally
{
DisposeImageCache(imageCache);
}
}
// --- Raw ---
/// <inheritdoc />
public async Task<byte[]> RenderToRaw(
Template layoutTemplate,
ObjectValue? data = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(layoutTemplate);
using var stream = new MemoryStream();
await RenderToRaw(stream, layoutTemplate, data, renderOptions, cancellationToken).ConfigureAwait(false);
return stream.ToArray();
}
/// <inheritdoc />
public async Task RenderToRaw(
Stream output,
Template layoutTemplate,
ObjectValue? data = null,
RenderOptions? renderOptions = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(layoutTemplate);
cancellationToken.ThrowIfCancellationRequested();
var effectiveData = data ?? new ObjectValue();
var (processedTemplate, imageCache) = await PreloadImages(layoutTemplate, effectiveData, cancellationToken)
.ConfigureAwait(false);
try
{
using var image = _engine.RenderToImage(processedTemplate, imageCache);
// Write raw RGBA pixel data
var pixelCount = checked(image.Width * image.Height);
var bufferSize = checked(pixelCount * 4);
var buffer = new byte[bufferSize];
image.CopyPixelDataTo(buffer);
await output.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
}
finally
{
DisposeImageCache(imageCache);
}
}
// ========================================================================
// IMAGE PRELOADING
// ========================================================================
/// <summary>
/// Expands and processes the template asynchronously, then pre-loads all images
/// referenced in it using the configured resource loaders.
/// </summary>
/// <param name="template">The template to process and scan for image references.</param>
/// <param name="data">The data context for expression evaluation.</param>
/// <param name="cancellationToken">Cancellation token for async operations.</param>
/// <returns>
/// A tuple of the fully processed template and an image cache. The processed template
/// is always non-null. The image cache maps URIs to pre-loaded images, or is <c>null</c>
/// when no images were found or no resource loaders are configured.
/// Caller is responsible for disposing images via <see cref="DisposeImageCache"/>.
/// </returns>
private async Task<(Template processedTemplate, Dictionary<string, Image<Rgba32>>? imageCache)> PreloadImages(
Template template,
ObjectValue data,
CancellationToken cancellationToken)
{
// Expand, resolve, and materialize template to resolve expressions in image src attributes
var expander = _filterRegistry is not null
? new TemplateExpander(_limits, _filterRegistry, _contentParserRegistry, _resourceLoaders)
: new TemplateExpander(_limits, _contentParserRegistry, _resourceLoaders);
var templateProcessor = _filterRegistry is not null
? new TemplateProcessor(_limits, _filterRegistry)
: new TemplateProcessor(_limits);
var pipeline = new TemplatePipeline(expander, templateProcessor);
var processedTemplate = await pipeline.ProcessAsync(template, data).ConfigureAwait(false);
if (_resourceLoaders.Count == 0)
return (processedTemplate, null);
var uris = ImageSharpRenderingEngine.CollectImageUris(processedTemplate);
if (uris.Count == 0)
return (processedTemplate, null);
var cache = new Dictionary<string, Image<Rgba32>>(
uris.Count, StringComparer.Ordinal);
foreach (var uri in uris)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var loader in _resourceLoaders
.OrderBy(l => l.Priority)
.Where(l => l.CanHandle(uri)))
{
var stream = await loader.Load(uri, cancellationToken)
.ConfigureAwait(false);
if (stream is not null)
{
using (stream)
{
var image = Image.Load<Rgba32>(stream);
cache[uri] = image;
}
break;
}
}
}
return (processedTemplate, cache.Count > 0 ? cache : null);
}
/// <summary>
/// Disposes all images in the pre-loaded image cache.
/// </summary>
/// <param name="imageCache">The cache to dispose, or <c>null</c>.</param>
private static void DisposeImageCache(
Dictionary<string, Image<Rgba32>>? imageCache)
{
if (imageCache is null)
return;
foreach (var image in imageCache.Values)
{
image.Dispose();
}
}
// ========================================================================
// DISPOSE
// ========================================================================
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
return;
_fontManager.Dispose();
foreach (var loader in _resourceLoaders)
{
if (loader is IDisposable disposable)
disposable.Dispose();
}
}
/// <summary>
/// Throws <see cref="ObjectDisposedException"/> if this instance has been disposed.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the renderer has been disposed.</exception>
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) == 1, this);
}
}