Skip to content

DW-41: Restore the ImageSharp conversions and ImageSharpLoader on .NET Framework without an ImageSharp dependency - #163

Open
Sawraz-IS wants to merge 2 commits into
system-memory-4.6-familyfrom
DW-41-net462-imagesharp-compat
Open

Sawraz-IS wants to merge 2 commits into
system-memory-4.6-familyfrom
DW-41-net462-imagesharp-compat

Conversation

@Sawraz-IS

Copy link
Copy Markdown
Collaborator

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 with MissingMethodException, including released IronPdf and IronBarCode, which call ImageSharpLoader.Load<Rgba32>.

This PR puts them all back on .NET Framework, without making ImageSharp a dependency again:

  • Apps that use these members add one package reference (SixLabors.ImageSharp 2.x). Their code, and libraries already compiled against older Drawing, then work without changes or a rebuild.
  • Apps that don't use them need nothing. ImageSharp is never loaded, every type still loads, and Assembly.GetTypes() works.
  • The net462 public API is now identical to netstandard2.0. Compared with 2027.1.1: 0 members removed, 47 added.

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.ImageSharp with PrivateAssets="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 to ImageSharpBridge (ImageSharpBridge.NetFramework.cs). The bridge converts between the SkiaEngine images and ImageSharp with non-generic pixel-format switches: no generics constrained to IPixel<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 public ImageSharpLoader name is free again. AnyBitmap calls the engine loader through a DecodeLoader alias.

  • Generic ImageSharpLoader.Load<TPixel>. Its IPixel<TPixel> constraint would make ImageSharpLoader fail to load without ImageSharp, which also breaks Assembly.GetTypes(). So after compiling the net462 build, build/StripImageSharpConstraints does three things:

    • removes that constraint from the two generic overloads (constraints aren't part of the signature callers bind to);
    • removes the one castclass Image<TPixel> the .NET Framework JIT would reject without the constraint;
    • strong-name signs the DLL again with the project key.

    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 can't reproduce the compiler's signature byte for byte;
    • any other generic code is constrained to an ImageSharp type;
    • the cast isn't where it expects;
    • anything is left to patch afterwards.

    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

  • Tests: net48 469/469, which re-enables the 62 ImageSharp conversion and loader tests and adds a generic-loader exception test. net481 (netstandard2.0 build) 452/452. net6/net8 run in CI (Six Labors licence).
  • Old binaries: a netstandard2.0 library compiled against Drawing 2026.11.5, run against this build on .NET Framework 4.8:
    • with ImageSharp 2.1.13: Color, geometry and AnyBitmap casts, non-generic and generic ImageSharpLoader.Load and GetTypes() all pass;
    • without ImageSharp: plain Drawing calls and GetTypes() pass. The ImageSharp calls need the package, as expected.
  • No ImageSharp present:
    • every type loads, GetTypes() works, and ImageSharp is never loaded;
    • reflection, serialization and AutoMapper probe outcomes are identical to 2027.1.1;
    • ILRepack still merges the DLL.
  • Strong name: sn.exe -vf reports the patched DLL valid, and a one-bit-tampered copy fails.
  • Builds: dotnet build and Visual Studio MSBuild, Debug and Release. Test-SystemAssemblyReferences.ps1 passes.

Not changed

  • netstandard2.0, net6 and net8 builds; nuspec dependency groups.
  • Known pre-existing issues remain: reflecting over every method signature fails on .NET Framework (unsigned Microsoft.Maui.Graphics, or ImageSharp types when it's absent), and Color has no parameterless constructor for JSON/DataContract deserialization.

…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 mee-ironsoftware left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Automated /scrutinize review — 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))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'">

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 castclass in the method body, which leaves unverifiable IL;
  • a reflection trampoline (ImageSharpLoader.cs LoadAs).

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.ImageSharpLoader follow 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 calls Image.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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ImageSharp 2.1.13.
  • Better still, have those products add the direct dependency in their next release.

{
return EngineToImageSharp(bitmap.GetImagesForImageSharpConversion());
}
catch (DllNotFoundException e)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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="&quot;$(StripImageSharpConstraintsDotnet)&quot; build &quot;$(StripImageSharpConstraintsProject)&quot; -c Release -o &quot;$(StripImageSharpConstraintsOutput.TrimEnd('\'))&quot; -nologo -v:q -nodeReuse:false" />

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ikkyuland left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, :121 say "malformed BigTIFF (.NET Standard 2.0 only)". ThrowIfUnsafe is under #if !NET6_0_OR_GREATER, so net462 also throws it now. Also ImageSharpLoader.cs:22 says "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:37 still 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>();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ suggestion — the pixel-format clone runs once per frame, not once per image. 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants