Repository navigation
DW-41: Restore the ImageSharp conversions and ImageSharpLoader on .NET Framework without an ImageSharp dependency - #163
Conversation
…er on .NET Framework through a compile-only ImageSharp reference, so code that uses them keeps working when the app references ImageSharp 2.x
…ET Framework by stripping their ImageSharp constraint after compiling and re-signing, so the assembly still loads without ImageSharp
mee-ironsoftware
left a comment
There was a problem hiding this comment.
🤖 Automated
/scrutinizereview — not yet read by@mee-ironsoftware.
Automated review — verdict: fix-then-ship
Blockers: 0 · Major: 3 · Nits: 2 — 5 inline, 0 in this body.
This is deliberately a comment only: it never approves and never requests changes. The verdict above is advisory; @mee-ironsoftware will follow up.
Restores the ImageSharp conversion operators and the public ImageSharpLoader on net462 as compile-only members, so ImageSharp loads only when a caller uses them. The bridge and the operators trace correctly. The core invariant, that the net462 assembly loads and GetTypes() works without ImageSharp, is checked only by hand and by code comments, and it depends on a post-compile IL patch and …
Full summary
Restores the ImageSharp conversion operators and the public ImageSharpLoader on net462 as compile-only members, so ImageSharp loads only when a caller uses them. The bridge and the operators trace correctly. The core invariant, that the net462 assembly loads and GetTypes() works without ImageSharp, is checked only by hand and by code comments, and it depends on a post-compile IL patch and strong-name re-sign that a type-forwarding design would avoid.
Reviewed head SHA 44f0532d7e16bab9cc388e5ae131a8ee532e519c. Re-request review on this PR to get a fresh pass.
| int tableStart = headers.MetadataStartOffset + md.GetTableMetadataOffset(TableIndex.GenericParamConstraint); | ||
| int rowSize = md.GetTableRowSize(TableIndex.GenericParamConstraint); | ||
|
|
||
| foreach (GenericParameterConstraintHandle handle in AllConstraints(md)) |
There was a problem hiding this comment.
Major: No automated guard for the 'loads without ImageSharp' invariant; the build tool only checks generic constraints
The PR's main promise for apps that don't use these members is that every type loads, Assembly.GetTypes() works and ImageSharp is never loaded. That was verified by hand. In CI, nothing can catch a regression: the test project references SixLabors.ImageSharp directly (IronSoftware.Drawing.Common.Tests.csproj:58), so ImageSharp is always present when tests run.
The build tool rejects only one way of breaking the invariant: an ImageSharp type in a generic constraint (Program.cs:90-104). Other ways that ImageSharpBridge.NetFramework.cs:15-18 itself documents are not checked:
- a field of an ImageSharp value type, for example
Rgba32, which the loader must resolve to lay out the type; - a lambda or local function that captures an ImageSharp struct, which gets a compiler-generated display class with such a field;
- an ImageSharp base type or interface.
Any of these in AnyBitmap, Color or the bridge would break GetTypes() for every net462 app that doesn't reference ImageSharp, and the build and tests would still pass.
Suggested change: add a net48 test that loads the built IronSoftware.Drawing.Common.dll where SixLabors.ImageSharp.dll can't be found, for example a child process or AppDomain whose probing directory leaves it out. The test should assert that GetTypes() succeeds and that ImageSharp is absent from AppDomain.GetAssemblies(). Alternatively, extend the tool to also fail on TypeDef field signatures, base types and interface implementations that reference the SixLabors.ImageSharp AssemblyRef.
| <StripImageSharpConstraintsDotnet Condition="'$(DOTNET_HOST_PATH)' == ''">dotnet</StripImageSharpConstraintsDotnet> | ||
| </PropertyGroup> | ||
|
|
||
| <Target Name="StripImageSharpConstraints" AfterTargets="CoreCompile" Condition="'$(TargetFramework)' == 'net462'"> |
There was a problem hiding this comment.
Major: Simpler alternative: type-forward ImageSharpLoader to a satellite assembly instead of patching IL and re-signing
The generic Load<TPixel> overloads drive the whole post-compile step:
- a hand-written strong-name signer (
Program.cs:327-425); - metadata-table patching of
GenericParamConstraint; - nop-ing a
castclassin the method body, which leaves unverifiable IL; - a reflection trampoline (
ImageSharpLoader.csLoadAs).
This is the most fragile part of the PR. It depends on reproducing the compiler's signing byte for byte, on an IL byte pattern, and on a nested dotnet build inside every net462 build.
On net462, ImageSharpLoader could instead live in a small strong-named satellite assembly, for example IronSoftware.Drawing.Common.ImageSharp.dll, shipped in the net462 lib folder. IronSoftware.Drawing.Common would then carry [assembly: TypeForwardedTo(typeof(ImageSharpLoader))]. Consequences:
- Callers compiled against netstandard2.0 that bind
[IronSoftware.Drawing.Common]IronSoftware.Drawing.ImageSharpLoaderfollow the forwarder. GetTypes()on Drawing.Common doesn't enumerate forwarded types, so it never touches the constraint.- The satellite keeps the real
IPixel<TPixel>constraint and callsImage.Load<TPixel>directly: no reflection, no IL patch, no re-sign.
Costs to weigh: one more DLL in the package, a check that ILRepack consumers handle the forwarder, and an InternalsVisibleTo if the loader needs Drawing internals (ThrowIfUnsafe could move with it). If the current approach is kept, the reason the forwarder was rejected belongs in the PR body, because maintainers will ask.
| Breaking Changes | ||
| - .NET Framework 4.6.2+ now has its own build that no longer depends on SixLabors.ImageSharp (2.x is end-of-life and no longer receives security fixes). Images are decoded, processed and encoded with SkiaSharp 4.153.3 and BitMiracle.LibTiff.NET instead | ||
| - On .NET Framework the implicit conversions between IronSoftware.Drawing types (AnyBitmap, Color, Point, PointF, Rectangle, RectangleF, Size, SizeF, CropRectangle) and SixLabors.ImageSharp types are no longer available. Libraries compiled against an earlier IronSoftware.System.Drawing that use those conversions must be rebuilt for .NET Framework | ||
| - On .NET Framework, the implicit conversions between IronSoftware.Drawing types (AnyBitmap, Color, Point, PointF, Rectangle, RectangleF, Size, SizeF, CropRectangle) and SixLabors.ImageSharp types, and ImageSharpLoader, need SixLabors.ImageSharp 2.x (2.1.13 recommended) referenced by the app, because it is no longer a dependency of this package. Code and libraries that use them keep working, without a rebuild, once the app references it. Apps that do not use them do not need ImageSharp |
There was a problem hiding this comment.
Major: 'Released IronPdf/IronBarCode work' holds only if the end app adds ImageSharp; the failure isn't actionable
The PR says released IronPdf and IronBarCode, which call ImageSharpLoader.Load<Rgba32>, work again. Traced: ImageSharpLoader.Load<TPixel> → LoadAs → reflection over typeof(Image). Referencing typeof(Image) loads SixLabors.ImageSharp, and the net462 nuspec group no longer brings it in.
Unless those released packages declare SixLabors.ImageSharp as their own direct net462 dependency (not checked here; before 2027.1.1 they got it transitively through Drawing), a .NET Framework app that upgrades only Drawing to 2027.1.2 still fails inside IronPdf or IronBarCode. The error is FileNotFoundException: Could not load file or assembly 'SixLabors.ImageSharp', thrown from Iron code the customer didn't write, so they have no hint that they need to add a package themselves.
The release-note line says to reference ImageSharp "if your code uses them". Customers in this situation don't know that their code uses them.
Suggested change:
- Check the net462 dependency groups of the latest released IronPdf and IronBarCode nuspecs.
- If ImageSharp is missing from them, say explicitly in the release notes (and in the DW-41 comms) that apps using IronPdf or IronBarCode versions up to X on .NET Framework must add
SixLabors.ImageSharp2.1.13. - Better still, have those products add the direct dependency in their next release.
| { | ||
| return EngineToImageSharp(bitmap.GetImagesForImageSharpConversion()); | ||
| } | ||
| catch (DllNotFoundException e) |
There was a problem hiding this comment.
Nit: The 'Please install SixLabors.ImageSharp' catch can't fire for a missing managed assembly
When ImageSharp is missing, the runtime throws FileNotFoundException (assembly load), not DllNotFoundException, and it throws while JIT-compiling the method whose body references ImageSharp types, before the try is entered. Here that method is the operator or the bridge method itself. So the four catch (DllNotFoundException) blocks (lines 41, 57, 82, 107) never give the friendly message. The AnyBitmap → Image direction, the one that runs without the caller holding an ImageSharp object, surfaces a raw FileNotFoundException from op_Implicit.
If the message matters, catch FileNotFoundException / FileLoadException in the AnyBitmap.ImageSharp.NetFramework.cs operators around the call into the bridge, which works because the bridge is JIT-compiled lazily. Otherwise, drop the dead catches.
| </PropertyGroup> | ||
|
|
||
| <Target Name="StripImageSharpConstraints" AfterTargets="CoreCompile" Condition="'$(TargetFramework)' == 'net462'"> | ||
| <Exec Command=""$(StripImageSharpConstraintsDotnet)" build "$(StripImageSharpConstraintsProject)" -c Release -o "$(StripImageSharpConstraintsOutput.TrimEnd('\'))" -nologo -v:q -nodeReuse:false" /> |
There was a problem hiding this comment.
Nit: The tool's dotnet build runs on every net462 build, with no Inputs/Outputs, into a shared in-tree output dir
The StripImageSharpConstraints target execs dotnet build of the tool project on every net462 inner build, including no-op incremental builds. It writes to a fixed build/StripImageSharpConstraints/bin/out/ and to the tool's shared obj/. That adds a nested restore and build to every inner-loop build. Two concurrent net462 builds, for example Debug and Release in parallel, or a pack run alongside an IDE build, race on the same output and obj files.
Consider building the tool once: a ProjectReference with ReferenceOutputAssembly=false, or Inputs/Outputs on the build step. Patching can also be skipped when CoreCompile didn't run; the tool is idempotent, but each run still re-hashes and re-checks the signature.
ikkyuland
left a comment
There was a problem hiding this comment.
Ikkyu's bot auto-review (not from human)
Status: COMMENT (no blocking issues)
This PR puts the ImageSharp conversion operators and the public ImageSharpLoader back into the net462 build, with SixLabors.ImageSharp as a compile-only reference. I traced the bridge in both directions (pixel-format switch, EnsureSameLayout, frame padding, GIF frame delays in 1/100 s on both sides, resolution metadata) and the reflection path of Load<TPixel>. I found no correctness bug. CI is green on net48, net48 x86, net481, net80 (Windows, Linux, macOS).
The earlier review on this head already covers the main risks: no automated "loads without ImageSharp" test, the type-forwarding alternative to the IL patch, the DllNotFoundException catch that cannot fire, and the tool build on every net462 build. I do not repeat them here. My notes are small and do not block the merge.
Findings not anchored to a changed line
⚠️ suggestion — stale doc: the BigTIFF check now also runs on .NET Framework.IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpLoader.cs:37,:50,:108,:121say "malformed BigTIFF (.NET Standard 2.0 only)".ThrowIfUnsafeis under#if !NET6_0_OR_GREATER, so net462 also throws it now. AlsoImageSharpLoader.cs:22says "On .NET Standard 2.0 (used by .NET Framework)", but .NET Framework has its own build since 2027.1.1. Suggest "(.NET Standard 2.0 and .NET Framework only)" and "On .NET Standard 2.0 and .NET Framework".⚠️ suggestion — stale csproj comment.IronSoftware.Drawing/IronSoftware.Drawing.Common/IronSoftware.Drawing.Common.csproj:37still starts with ".NET Framework: no SixLabors.ImageSharp." The same<When>block now adds a compile-only ImageSharp reference. Suggest ".NET Framework: no SixLabors.ImageSharp runtime dependency (compile-only reference, see below)."
| { | ||
| E.Image source = frames[f].Key; | ||
| int index = frames[f].Value; | ||
| E.Image<TE> typed = source as E.Image<TE> ?? source.CloneAs<TE>(); |
There was a problem hiding this comment.
frames is flattened, so when a source image has N frames and a pixel type that is not TE, source.CloneAs<TE>() copies all N frames on each of the N iterations (N² frame copies). The result is correct, and the case is rare (a multi-frame image after a root of another pixel type). A small cache fixes it, for example keep the last (source, typed) pair and clone only when source changes:
E.Image lastSource = null; E.Image<TE> lastTyped = null;
...
if (!ReferenceEquals(source, lastSource)) { lastSource = source; lastTyped = source as E.Image<TE> ?? source.CloneAs<TE>(); }
E.Image<TE> typed = lastTyped;(bot)
Summary
2027.1.1 dropped every ImageSharp member from the .NET Framework (net462) build: the implicit conversions on AnyBitmap, Color, Point, PointF, Rectangle, RectangleF, Size, SizeF and CropRectangle, and the public
ImageSharpLoader. Customer code and libraries compiled against an earlier Drawing that use them fail on .NET Framework withMissingMethodException, including released IronPdf and IronBarCode, which callImageSharpLoader.Load<Rgba32>.This PR puts them all back on .NET Framework, without making ImageSharp a dependency again:
Assembly.GetTypes()works.Targets this as Drawing 2027.1.2. Stacked on #159 (base
system-memory-4.6-family); it moves to develop when #159 merges.How it works
Compile-only reference. net462 references
SixLabors.ImageSharpwithPrivateAssets="all" ExcludeAssets="runtime", so it is not in the nuspec net462 group. .NET Framework loads it only when one of these members actually runs.No ImageSharp types in AnyBitmap's layout. The AnyBitmap operators (
AnyBitmap.ImageSharp.NetFramework.cs) only forward toImageSharpBridge(ImageSharpBridge.NetFramework.cs). The bridge converts between the SkiaEngine images and ImageSharp with non-generic pixel-format switches: no generics constrained toIPixel<T>, no lambdas. That keeps the .NET Framework type loader from resolving ImageSharp when AnyBitmap loads. Images decode with the engine, so ImageSharp's decoders never run on caller bytes.The internal SkiaEngine loader is renamed
EngineLoader, so the publicImageSharpLoadername is free again. AnyBitmap calls the engine loader through aDecodeLoaderalias.Generic
ImageSharpLoader.Load<TPixel>. ItsIPixel<TPixel>constraint would make ImageSharpLoader fail to load without ImageSharp, which also breaksAssembly.GetTypes(). So after compiling the net462 build,build/StripImageSharpConstraintsdoes three things:castclass Image<TPixel>the .NET Framework JIT would reject without the constraint;On .NET Framework the method body calls
Image.Load<TPixel>through reflection, which checks the real pixel type and rethrows ImageSharp's own exceptions unwrapped. The tool fails the build if:It is idempotent, runs on the obj\ DLL before the copy to bin, targets the SDK's bundled runtime and has no package references. Reference assemblies keep the constraint for compile-time callers.
Release notes in the nuspec updated.
Testing
ImageSharpLoader.LoadandGetTypes()all pass;GetTypes()pass. The ImageSharp calls need the package, as expected.GetTypes()works, and ImageSharp is never loaded;sn.exe -vfreports the patched DLL valid, and a one-bit-tampered copy fails.dotnet buildand Visual Studio MSBuild, Debug and Release.Test-SystemAssemblyReferences.ps1passes.Not changed
Colorhas no parameterless constructor for JSON/DataContract deserialization.