diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/AnyBitmapFunctionality.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/AnyBitmapFunctionality.cs index 27041223..dffca62d 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/AnyBitmapFunctionality.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/AnyBitmapFunctionality.cs @@ -250,7 +250,6 @@ public void AnyBitmap_should_get_Bytes() Assert.Equal(expected, resultExport); } -#if !NET48 [FactWithAutomaticDisplayName] public void AnyBitmap_should_set_Pixel() { @@ -291,7 +290,6 @@ public void AnyBitmap_should_set_Pixel() #endif } } -#endif [FactWithAutomaticDisplayName] public void AnyBitmap_should_get_Stream() @@ -341,7 +339,6 @@ public void AnyBitmap_should_ToString() Assert.Equal(expected, result); } -#if !NET48 [FactWithAutomaticDisplayName] public void AnyBitmap_GetPixel_should_not_throw_OutOfMemoryException() { @@ -393,7 +390,6 @@ public void Clone_AnyBitmap() AssertImageAreEqual("expected.png", "result.png", true); } -#endif [FactWithAutomaticDisplayName] public void Clone_Crop_AnyBitmap() @@ -477,7 +473,6 @@ public void CastSKImage_from_AnyBitmap() AssertImageAreEqual("expected.png", "result.png", true); } -#if !NET48 [FactWithAutomaticDisplayName] public void CastSixLabors_to_AnyBitmap() { @@ -538,7 +533,6 @@ public void CastSixLabors_from_AnyBitmap_Rgba32(string filename) AssertImageAreEqual("expected.bmp", "result.bmp", true); } -#endif [FactWithAutomaticDisplayName] public void CastBitmap_to_AnyBitmap_using_FromBitmap() @@ -717,7 +711,6 @@ public void Create_Multi_page_Tiff_Paths() File.Delete(outputImagePath); } -#if !NET48 [FactWithAutomaticDisplayName] public void CreateMultiFrameTiffStream_Preserves_Mixed_Orientation() { @@ -760,7 +753,6 @@ public void CreateMultiFrameTiffBytes_Preserves_Per_Page_Dimensions_And_Resoluti .Should().BeApproximately(150d, 2d); } } -#endif [FactWithAutomaticDisplayName] public void CreateMultiFrameTiffStream_Empty_Sequence_Throws() @@ -769,7 +761,6 @@ public void CreateMultiFrameTiffStream_Empty_Sequence_Throws() act.Should().Throw(); } -#if !NET48 [FactWithAutomaticDisplayName] public void CreateMultiFrameTiffBytes_PreservesResolution_FromPixelsPerMeterSource() { @@ -786,7 +777,6 @@ public void CreateMultiFrameTiffBytes_PreservesResolution_FromPixelsPerMeterSour ToDotsPerInch(pages[0].XResolution, pages[0].ResolutionUnit) .Should().BeApproximately(dpi, 2d); } -#endif [FactWithAutomaticDisplayName] public void CreateMultiFrameTiff_Preserves_Rgb24_Pixels() @@ -828,7 +818,6 @@ public void CreateMultiFrameTiff_Preserves_Rgb24_Pixels() } } -#if !NET48 [TheoryWithAutomaticDisplayName] [InlineData("Rgb24")] [InlineData("Bgr24")] @@ -893,7 +882,6 @@ private static AnyBitmap MakeBitmapWithResolution(int width, int height, Rgb24 c image.Metadata.ResolutionUnits = unit; return image; } -#endif private static List<(int Width, int Height, float XResolution, ResUnit ResolutionUnit)> ReadTiffDirectories(byte[] tiffData) { @@ -934,7 +922,6 @@ private static double ToDotsPerInch(float xResolution, ResUnit unit) }; } -#if !NET48 [FactWithAutomaticDisplayName] public void Create_Multi_page_Gif() { @@ -1010,7 +997,6 @@ public void Should_Return_BitsPerPixel() bitmap = Image.Load(GetRelativeFilePath("mountainclimbers.jpg")); Assert.Equal(32, bitmap.BitsPerPixel); } -#endif [TheoryWithAutomaticDisplayName] [InlineData("ScanDev_BW.tif", 1)] @@ -1196,7 +1182,6 @@ public void Resize_ShouldPreserveDepthForRepresentableFormats() } } -#if !NET48 [TheoryWithAutomaticDisplayName] [InlineData("A8", "GrayscaleWithAlpha", "Bit8", 16)] [InlineData("L8", "Grayscale", "Bit8", 8)] @@ -1243,7 +1228,6 @@ public void ExportPng_ShouldChooseColorTypeAndBitDepthFromPixelType( } Assert.Equal(expectedBitsPerPixel, AnyBitmap.FromBytes(png).BitsPerPixel); } -#endif [TheoryWithAutomaticDisplayName] [InlineData("Palette", "Bit8")] @@ -1394,7 +1378,6 @@ public void Should_RotateFlip() AssertImageAreEqual(GetRelativeFilePath("checkmarkFlip.jpg"), "result_flip.bmp"); } -#if !NET48 [FactWithAutomaticDisplayName] public void Redact_ShouldRedactRegionWithColor() { @@ -1435,7 +1418,6 @@ public void Redact_ShouldRedactRegionWithColor() } } } -#endif [FactWithAutomaticDisplayName] public void TestGetRGBBuffer() @@ -1681,7 +1663,6 @@ public void LoadImage_SetPreserveOriginalFormat_ShouldReturnCorrectBitPerPixel(s } #if !NET7_0 -#if !NET48 [FactWithAutomaticDisplayName] public void CastAnyBitmap_from_SixLabors() { @@ -1697,7 +1678,6 @@ public void CastAnyBitmap_from_SixLabors() AssertLargeImageAreEqual("expected.bmp", "result.bmp", true); } #endif -#endif [IgnoreOnAzureDevopsX86Fact] diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/ColorFunctionality.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/ColorFunctionality.cs index 79a5e8eb..08bdb1d5 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/ColorFunctionality.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/ColorFunctionality.cs @@ -274,7 +274,6 @@ public void Cast_SKColor_to_Color() Assert.Equal(176, skColor.Blue); } -#if !NET48 [FactWithAutomaticDisplayName] public void Cast_ImageSharp_Color_from_Color() { @@ -558,7 +557,6 @@ public void Should_Return_Argb() Assert.Equal(bmColor.ToArgb(), rgba32.ToArgb()); Assert.Equal(bmColor.ToArgb(), rgb24.ToArgb()); } -#endif [FactWithAutomaticDisplayName] public void Should_Create_FromName() diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/Compare.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/Compare.cs index 58c13a7b..bc4a4a28 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/Compare.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/Compare.cs @@ -25,23 +25,9 @@ protected static void AssertLargeImageAreEqual(string expectedImagePath, string expectedImageSharp.Mutate(x => x.Resize(100, 100)); actualImageSharp.Mutate(x => x.Resize(100, 100)); -#if NET48 - // The ImageSharp casts are not available on .NET Framework; go through PNG bytes instead. - AssertImageAreEqual(ToAnyBitmap(expectedImageSharp), ToAnyBitmap(actualImageSharp)); -#else AssertImageAreEqual(expectedImageSharp, actualImageSharp); -#endif } -#if NET48 - private static AnyBitmap ToAnyBitmap(SixLabors.ImageSharp.Image image) - { - using var stream = new MemoryStream(); - SixLabors.ImageSharp.ImageExtensions.SaveAsPng(image, stream); - return AnyBitmap.FromBytes(stream.ToArray()); - } -#endif - protected static void AssertImageAreEqual(string expectedImagePath, string resultImagePath, bool isCleanAll = false) { using var expected = AnyBitmap.FromFile(expectedImagePath); diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/RectangleFunctionality.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/RectangleFunctionality.cs index 64edcb6c..a12e3ad5 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/RectangleFunctionality.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/RectangleFunctionality.cs @@ -70,7 +70,6 @@ public void CastRectangle_from_Rectangle() Assert.Equal(5, rectangle.Y); } -#if !NET48 [FactWithAutomaticDisplayName] public void CastImageSharp_Rectangle_to_Rectangle() { @@ -138,7 +137,6 @@ public void CastImageSharp_RectangleF_from_Rectangle() Assert.Equal(5, rectangle.X); Assert.Equal(5, rectangle.Y); } -#endif [FactWithAutomaticDisplayName] public void CastSKRect_to_Rectangle() @@ -413,7 +411,6 @@ public void CastRectangleF_from_RectangleF() Assert.Equal(5, Rectangle.Y); } -#if !NET48 [FactWithAutomaticDisplayName] public void CastImageSharp_RectangleF_to_RectangleF() { @@ -446,7 +443,6 @@ public void CastImageSharp_RectangleF_from_RectangleF() Assert.Equal(5, Rectangle.X); Assert.Equal(5, Rectangle.Y); } -#endif [FactWithAutomaticDisplayName] public void CastSKRect_to_RectangleF() diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/TiffDirectoryGuardFunctionality.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/TiffDirectoryGuardFunctionality.cs index bf17dccd..db2cff23 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/TiffDirectoryGuardFunctionality.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common.Tests/UnitTests/TiffDirectoryGuardFunctionality.cs @@ -129,19 +129,16 @@ public void CreateMultiFrameTiff_BigTiffWithOversizedIfdCount_FailsFast() } } -#if !NET48 [FactWithAutomaticDisplayName] public void ImageSharpLoader_BigTiffWithOversizedIfdCount_FailsFast() { byte[] bytes = CreateBigTiffWithOversizedIfdCount(); ShouldFailFast(() => ImageSharpLoader.Load(bytes)); - ShouldFailFast(() => ImageSharpLoader.Load(bytes)); ShouldFailFast(() => ImageSharpLoader.Load(new MemoryStream(bytes))); + ShouldFailFast(() => ImageSharpLoader.Load(bytes)); ShouldFailFast(() => ImageSharpLoader.Load(new MemoryStream(bytes))); } -#endif -#if !NET48 [FactWithAutomaticDisplayName] public void ImageSharpLoader_ValidImage_MatchesImageLoad() { @@ -150,14 +147,26 @@ public void ImageSharpLoader_ValidImage_MatchesImageLoad() using var expected = SixLabors.ImageSharp.Image.Load(bytes); using var fromBytes = ImageSharpLoader.Load(bytes); using var fromStream = ImageSharpLoader.Load(new MemoryStream(bytes)); + using var typedFromStream = ImageSharpLoader.Load(new MemoryStream(bytes)); fromBytes.Width.Should().Be(expected.Width); fromBytes.Height.Should().Be(expected.Height); fromBytes[10, 10].Should().Be(expected[10, 10]); fromStream.Width.Should().Be(expected.Width); fromStream.Height.Should().Be(expected.Height); + typedFromStream.Width.Should().Be(expected.Width); + typedFromStream[10, 10].Should().Be(expected[10, 10].Rgb); + } + + [FactWithAutomaticDisplayName] + public void ImageSharpLoader_GenericLoad_InvalidData_ThrowsImageSharpException() + { + // On .NET Framework the generic overloads call ImageSharp through reflection; callers must still get + // ImageSharp's own exception, not a TargetInvocationException. + byte[] garbage = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; + Action load = () => ImageSharpLoader.Load(garbage); + load.Should().Throw(); } -#endif [FactWithAutomaticDisplayName] public void FromBytes_ValidBigTiff_StillLoads() diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.ImageSharp.NetFramework.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.ImageSharp.NetFramework.cs new file mode 100644 index 00000000..baedf8ea --- /dev/null +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.ImageSharp.NetFramework.cs @@ -0,0 +1,132 @@ +#if NETFRAMEWORK +using System.Collections.Generic; +using E = IronSoftware.Drawing.SkiaEngine; +using IS = SixLabors.ImageSharp; +using ISP = SixLabors.ImageSharp.PixelFormats; + +namespace IronSoftware.Drawing +{ + // .NET Framework: the ImageSharp conversion operators of the other targets, kept for source and binary + // compatibility. SixLabors.ImageSharp is a compile-time-only reference here (not a package dependency), and + // .NET Framework loads it only when one of these operators runs, which means the caller references ImageSharp + // itself. + // + // Keep AnyBitmap free of any other ImageSharp type: the type loader resolves the types used in generic + // constraints, fields, base types and the like when it loads AnyBitmap, so a single generic helper constrained + // to ImageSharp's IPixel here would make every use of AnyBitmap fail without ImageSharp. The operators only + // forward to ImageSharpBridge, which is loaded the first time one of them runs. + public partial class AnyBitmap + { + /// + /// Implicitly casts SixLabors.ImageSharp.Image objects to + /// . + /// When your .NET Class methods use as + /// parameters or return types, you now automatically support ImageSharp + /// as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original SixLabors.ImageSharp.Image object + /// to avoid unnecessary memory allocation. + /// + /// SixLabors.ImageSharp.Image will automatically + /// be casted to . + public static implicit operator AnyBitmap(IS.Image image) => ImageSharpBridge.ToAnyBitmap(image); + + /// + /// Implicitly casts to SixLabors.ImageSharp.Image objects from + /// . + /// When your .NET Class methods use + /// as parameters or return types, you now automatically support + /// ImageSharp as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original IronSoftware.Drawing.AnyBitmap object + /// to avoid unnecessary memory allocation. + /// + /// is implicitly cast to + /// a SixLabors.ImageSharp.Image. + public static implicit operator IS.Image(AnyBitmap bitmap) => ImageSharpBridge.ToImageSharpRgb24(bitmap); + + /// + /// Implicitly casts SixLabors.ImageSharp.Image objects to + /// . + /// When your .NET Class methods use as + /// parameters or return types, you now automatically support ImageSharp + /// as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original SixLabors.ImageSharp.Image object + /// to avoid unnecessary memory allocation. + /// + /// SixLabors.ImageSharp.Image will automatically be + /// cast to . + public static implicit operator AnyBitmap(IS.Image image) => ImageSharpBridge.ToAnyBitmap(image); + + /// + /// Implicitly casts to SixLabors.ImageSharp.Image objects from + /// . + /// When your .NET Class methods use as + /// parameters or return types, you now automatically support ImageSharp + /// as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original IronSoftware.Drawing.AnyBitmap object + /// to avoid unnecessary memory allocation. + /// + /// is implicitly cast to + /// a SixLabors.ImageSharp.Image. + public static implicit operator IS.Image(AnyBitmap bitmap) => ImageSharpBridge.ToImageSharpRgba32(bitmap); + + /// + /// Implicitly casts SixLabors.ImageSharp.Image objects to + /// . + /// When your .NET Class methods use as + /// parameters or return types, you now automatically support ImageSharp + /// as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original SixLabors.ImageSharp.Image object + /// to avoid unnecessary memory allocation. + /// + /// SixLabors.ImageSharp.Image will automatically + /// be casted to . + public static implicit operator AnyBitmap(IS.Image image) => ImageSharpBridge.ToAnyBitmap(image); + + /// + /// Implicitly casts to SixLabors.ImageSharp.Image objects from + /// . + /// When your .NET Class methods use as + /// parameters or return types, you now automatically support ImageSharp + /// as well. + /// On .NET Framework, SixLabors.ImageSharp is not a dependency of this package: reference + /// SixLabors.ImageSharp 2.x in your project to use this conversion. + /// When casting to and from AnyBitmap, + /// please remember to dispose your original IronSoftware.Drawing.AnyBitmap object + /// to avoid unnecessary memory allocation. + /// + /// is implicitly cast to + /// a SixLabors.ImageSharp.Image. + public static implicit operator IS.Image(AnyBitmap bitmap) => ImageSharpBridge.ToImageSharp(bitmap); + + /// + /// The engine images an ImageSharp conversion starts from (no ImageSharp types, see above). Like the other + /// targets, an AnyBitmap that has not been decoded yet (and is not TIFF or GIF) converts straight from its + /// bytes, without AnyBitmap's load-time corrections (EXIF auto-orient, DPI normalisation). + /// + internal IReadOnlyList GetImagesForImageSharpConversion() + { + if (!IsImageLoaded() && Format is not E.TiffFormat && Format is not E.GifFormat) + { + return new[] { E.Image.Load(Binary) }; + } + + return GetInternalImages(); + } + } +} +#endif diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs index 9bf4f7f0..be1513d1 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs @@ -6,6 +6,8 @@ using EngineRotateMode = IronSoftware.Drawing.SkiaEngine.RotateMode; using EngineFlipMode = IronSoftware.Drawing.SkiaEngine.FlipMode; using EnginePixelResolutionUnit = IronSoftware.Drawing.SkiaEngine.PixelResolutionUnit; +// Not ImageSharpLoader: that public type also exists on .NET Framework and would load SixLabors.ImageSharp. +using DecodeLoader = IronSoftware.Drawing.SkiaEngine.EngineLoader; #else using SixLabors.ImageSharp; using SixLabors.ImageSharp.Drawing.Processing; @@ -22,6 +24,7 @@ using EngineRotateMode = SixLabors.ImageSharp.Processing.RotateMode; using EngineFlipMode = SixLabors.ImageSharp.Processing.FlipMode; using EnginePixelResolutionUnit = SixLabors.ImageSharp.Metadata.PixelResolutionUnit; +using DecodeLoader = IronSoftware.Drawing.ImageSharpLoader; #endif using SkiaSharp; using System; @@ -1236,7 +1239,7 @@ public IEnumerable GetAllFrames public static AnyBitmap CreateMultiFrameTiff(IEnumerable imagePaths) { using var stream = new MemoryStream(); - InternalSaveAsMultiPageTiff(imagePaths.Select(path => ImageSharpLoader.Load(File.ReadAllBytes(path))), stream); + InternalSaveAsMultiPageTiff(imagePaths.Select(path => DecodeLoader.Load(File.ReadAllBytes(path))), stream); return FromStream(stream); } @@ -1330,7 +1333,7 @@ public static byte[] CreateMultiFrameTiffBytes(IEnumerable images) public static AnyBitmap CreateMultiFrameGif(IEnumerable imagePaths) { using var stream = new MemoryStream(); - InternalSaveAsMultiPageGif(imagePaths.Select(path => ImageSharpLoader.Load(File.ReadAllBytes(path))), stream); + InternalSaveAsMultiPageGif(imagePaths.Select(path => DecodeLoader.Load(File.ReadAllBytes(path))), stream); return FromStream(stream); } @@ -1498,7 +1501,7 @@ public static AnyBitmap RotateFlip( _ => throw new NotImplementedException() }; - Image image = ImageSharpLoader.Load(bitmap.Binary); + Image image = DecodeLoader.Load(bitmap.Binary); image.Mutate(x => x.RotateFlip(rotateModeImgSharp, flipModeImgSharp)); @@ -1536,7 +1539,7 @@ public static AnyBitmap Redact( { //this casting will crate new object - Image image = ImageSharpLoader.Load(bitmap.Binary); + Image image = DecodeLoader.Load(bitmap.Binary); Rectangle rectangle = Rectangle; var brush = new SolidBrush(color); #if NET8_0_OR_GREATER @@ -2126,7 +2129,7 @@ private static Image CastToImageSharp(AnyBitmap bitmap) var format = bitmap.Format; if (format is not TiffFormat && format is not GifFormat) { - return ImageSharpLoader.Load(bitmap.Binary); + return DecodeLoader.Load(bitmap.Binary); } } @@ -2187,7 +2190,7 @@ private static Image CastToImageSharp(AnyBitmap bitmap) where T :unmanaged var format = bitmap.Format; if (format is not TiffFormat && format is not GifFormat) { - return ImageSharpLoader.Load(bitmap.Binary); + return DecodeLoader.Load(bitmap.Binary); } } @@ -3441,12 +3444,12 @@ private Lazy> OpenImageToImageSharp(bool preserveOriginalFo Image img; if (preserveOriginalFormat) { - img = ImageSharpLoader.Load(Binary); + img = DecodeLoader.Load(Binary); } else { PreserveOriginalFormat = preserveOriginalFormat; - img = ImageSharpLoader.Load(Binary); + img = DecodeLoader.Load(Binary); if (Format.Name == "PNG") img.Mutate(img => img.BackgroundColor(Color.White)); } diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Color.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Color.cs index e93aaed7..fc36d145 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Color.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Color.cs @@ -1048,7 +1048,6 @@ public static implicit operator SkiaSharp.SKColor(Color color) return new SkiaSharp.SKColor(color.R, color.G, color.B, color.A); } -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1059,9 +1058,7 @@ public static implicit operator Color(SixLabors.ImageSharp.Color color) string hex = color.ToHex(); return new Color(ConvertToHexNumberByte(hex, 6, 2), ConvertToHexNumberByte(hex, 0, 2), ConvertToHexNumberByte(hex, 2, 2), ConvertToHexNumberByte(hex, 4, 2)); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1075,9 +1072,7 @@ public static implicit operator SixLabors.ImageSharp.Color(Color color) return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1088,9 +1083,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Rgba32 c string hex = color.ToHex(); // Rgba return new Color(ConvertToHexNumberByte(hex, 6, 2), ConvertToHexNumberByte(hex, 0, 2), ConvertToHexNumberByte(hex, 2, 2), ConvertToHexNumberByte(hex, 4, 2)); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1104,9 +1097,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Rgba32(Color c return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1116,9 +1107,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Bgra32 c { return new Color(color.A, color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1132,9 +1121,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Bgra32(Color c return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1144,9 +1131,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Rgb24 co { return new Color(color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1160,9 +1145,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Rgb24(Color co return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1172,9 +1155,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Bgr24 co { return new Color(color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1188,9 +1169,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Bgr24(Color co return SixLabors.ImageSharp.Color.FromRgb(color.R, color.G, color.B); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1204,9 +1183,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Rgb48 co return (Color)SixLabors.ImageSharp.Color.FromRgb((byte)(color.R >> 8), (byte)(color.G >> 8), (byte)(color.B >> 8)); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1222,9 +1199,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Rgb48(Color co return result; #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1234,9 +1209,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Rgba64 c { return new Color(color.A, color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1250,9 +1223,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Rgba64(Color c return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1262,9 +1233,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Abgr32 c { return new Color(color.A, color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1278,9 +1247,7 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Abgr32(Color c return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts objects to . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1290,9 +1257,7 @@ public static implicit operator Color(SixLabors.ImageSharp.PixelFormats.Argb32 c { return new Color(color.A, color.R, color.G, color.B); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to objects from . /// When your .NET Class methods use as parameters or return types, you now automatically support as well. @@ -1306,7 +1271,6 @@ public static implicit operator SixLabors.ImageSharp.PixelFormats.Argb32(Color c return SixLabors.ImageSharp.Color.FromRgba(color.R, color.G, color.B, color.A); #endif } -#endif /// /// Implicitly casts objects to . diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpBridge.NetFramework.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpBridge.NetFramework.cs new file mode 100644 index 00000000..4f014ed3 --- /dev/null +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpBridge.NetFramework.cs @@ -0,0 +1,358 @@ +#if NETFRAMEWORK +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using E = IronSoftware.Drawing.SkiaEngine; +using IS = SixLabors.ImageSharp; +using ISP = SixLabors.ImageSharp.PixelFormats; + +namespace IronSoftware.Drawing +{ + /// + /// .NET Framework implementation of AnyBitmap's ImageSharp conversion operators. Only those operators use this + /// class, so .NET Framework loads SixLabors.ImageSharp the first time one of them runs. + /// This type must load without ImageSharp (Assembly.GetTypes() loads every type): no generic parameter + /// constrained to an ImageSharp type, and no lambdas or method-group delegates (their compiler-generated types + /// would have ImageSharp-typed fields). ImageSharp generics appear only as closed instantiations in method + /// bodies, which the JIT resolves when the method first runs. + /// Differences from the other targets, by design: + /// + /// Images are decoded by the SkiaSharp/LibTiff engine and handed to ImageSharp as pixel data, so ImageSharp's + /// 2.x decoders never run on the caller's bytes here (only its in-memory image types are used). + /// The returned ImageSharp image is always a copy; on the other targets it can be AnyBitmap's own instance. + /// + /// + internal static class ImageSharpBridge + { + /// The pixel formats that exist with the same byte layout in the engine and in ImageSharp. + private enum Kind + { + Rgba32, Bgra32, Abgr32, Argb32, Rgb24, Bgr24, L8, L16, La16, La32, A8, Rgb48, Rgba64, Other + } + + public static AnyBitmap ToAnyBitmap(IS.Image image) + { + try + { + // The other targets wrap a null image the same way (and fail later when it is used). + return image == null ? new AnyBitmap((E.Image)null) : new AnyBitmap(ImageSharpToEngine(image)); + } + catch (DllNotFoundException e) + { + throw new DllNotFoundException("Please install SixLabors.ImageSharp from NuGet.", e); + } + catch (Exception e) + { + throw new NotSupportedException("Error while casting AnyBitmap from SixLabors.ImageSharp.Image", e); + } + } + + public static IS.Image ToImageSharp(AnyBitmap bitmap) + { + try + { + return EngineToImageSharp(bitmap.GetImagesForImageSharpConversion()); + } + catch (DllNotFoundException e) + { + throw new DllNotFoundException("Please install SixLabors.ImageSharp from NuGet.", e); + } + catch (Exception e) + { + throw new NotSupportedException("Error while casting AnyBitmap to SixLabors.ImageSharp.Image", e); + } + } + + public static IS.Image ToImageSharpRgb24(AnyBitmap bitmap) + { + try + { + IS.Image image = EngineToImageSharp(bitmap.GetImagesForImageSharpConversion()); + if (image is IS.Image typed) + { + return typed; + } + + using (image) + { + return image.CloneAs(); + } + } + catch (DllNotFoundException e) + { + throw new DllNotFoundException("Please install SixLabors.ImageSharp from NuGet.", e); + } + catch (Exception e) + { + throw new NotSupportedException("Error while casting AnyBitmap to SixLabors.ImageSharp.Image", e); + } + } + + public static IS.Image ToImageSharpRgba32(AnyBitmap bitmap) + { + try + { + IS.Image image = EngineToImageSharp(bitmap.GetImagesForImageSharpConversion()); + if (image is IS.Image typed) + { + return typed; + } + + using (image) + { + return image.CloneAs(); + } + } + catch (DllNotFoundException e) + { + throw new DllNotFoundException("Please install SixLabors.ImageSharp from NuGet.", e); + } + catch (Exception e) + { + throw new NotSupportedException("Error while casting AnyBitmap to SixLabors.ImageSharp.Image", e); + } + } + + // ---- engine -> ImageSharp ------------------------------------------------------------------------- + + private static IS.Image EngineToImageSharp(IReadOnlyList images) + { + // Flatten to frames; like the other targets, frames of a different size are padded to the first one. + var frames = new List>(); + foreach (E.Image image in images) + { + for (int i = 0; i < image.FrameCount; i++) + { + frames.Add(new KeyValuePair(image, i)); + } + } + + E.Image root = images[0]; + switch (KindOf(root)) + { + case Kind.Bgra32: return Build(frames, root, Kind.Bgra32); + case Kind.Abgr32: return Build(frames, root, Kind.Abgr32); + case Kind.Argb32: return Build(frames, root, Kind.Argb32); + case Kind.Rgb24: return Build(frames, root, Kind.Rgb24); + case Kind.Bgr24: return Build(frames, root, Kind.Bgr24); + case Kind.L8: return Build(frames, root, Kind.L8); + case Kind.L16: return Build(frames, root, Kind.L16); + case Kind.La16: return Build(frames, root, Kind.La16); + case Kind.La32: return Build(frames, root, Kind.La32); + case Kind.A8: return Build(frames, root, Kind.A8); + case Kind.Rgb48: return Build(frames, root, Kind.Rgb48); + case Kind.Rgba64: return Build(frames, root, Kind.Rgba64); + default: return Build(frames, root, Kind.Rgba32); + } + } + + private static IS.Image Build(List> frames, E.Image root, Kind kind) + where TE : unmanaged, E.IPixel + { + int width = root.Width, height = root.Height; + IS.Image result = null; + try + { + for (int f = 0; f < frames.Count; f++) + { + E.Image source = frames[f].Key; + int index = frames[f].Value; + E.Image typed = source as E.Image ?? source.CloneAs(); + TE[] pixels = typed.GetFramePixels(index); + if (typed.Width != width || typed.Height != height) + { + var single = (E.Image)typed.CloneFrameInternal(index); + single.ApplyBoxPad(width, height, Color.Transparent); + pixels = single.GetFramePixels(0); + } + + IS.Image frameImage = LoadPixelData(kind, MemoryMarshal.AsBytes(pixels.AsSpan()), width, height, Unsafe.SizeOf()); + if (result == null) + { + result = frameImage; + } + else + { + using (frameImage) + { + result.Frames.AddFrame(frameImage.Frames.RootFrame); + } + } + + List delays = root.Metadata.FrameDelays; + if (delays != null && f < delays.Count) + { + IS.MetadataExtensions.GetGifMetadata(result.Frames[f].Metadata).FrameDelay = delays[f]; + } + } + + result.Metadata.HorizontalResolution = root.Metadata.HorizontalResolution; + result.Metadata.VerticalResolution = root.Metadata.VerticalResolution; + result.Metadata.ResolutionUnits = (IS.Metadata.PixelResolutionUnit)(byte)root.Metadata.ResolutionUnits; + return result; + } + catch + { + result?.Dispose(); + throw; + } + } + + private static IS.Image LoadPixelData(Kind kind, ReadOnlySpan bytes, int width, int height, int enginePixelSize) + { + IS.Image image = kind switch + { + Kind.Rgba32 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Bgra32 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Abgr32 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Argb32 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Rgb24 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Bgr24 => IS.Image.LoadPixelData(bytes, width, height), + Kind.L8 => IS.Image.LoadPixelData(bytes, width, height), + Kind.L16 => IS.Image.LoadPixelData(bytes, width, height), + Kind.La16 => IS.Image.LoadPixelData(bytes, width, height), + Kind.La32 => IS.Image.LoadPixelData(bytes, width, height), + Kind.A8 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Rgb48 => IS.Image.LoadPixelData(bytes, width, height), + Kind.Rgba64 => IS.Image.LoadPixelData(bytes, width, height), + _ => throw new NotSupportedException($"Unsupported pixel format {kind}."), + }; + EnsureSameLayout(enginePixelSize, image); + return image; + } + + // ---- ImageSharp -> engine ------------------------------------------------------------------------- + + private static E.Image ImageSharpToEngine(IS.Image image) + { + Kind kind = KindOf(image); + if (kind == Kind.Other) + { + // Pixel formats the engine has no exact match for: keep 16 bits per channel when the source has + // more than 8, otherwise 8. + if (image.PixelType.BitsPerPixel > 32) + { + using IS.Image wide = image.CloneAs(); + return ImageSharpToEngine(wide); + } + + using IS.Image narrow = image.CloneAs(); + return ImageSharpToEngine(narrow); + } + + switch (kind) + { + case Kind.Bgra32: return Copy(image, kind); + case Kind.Abgr32: return Copy(image, kind); + case Kind.Argb32: return Copy(image, kind); + case Kind.Rgb24: return Copy(image, kind); + case Kind.Bgr24: return Copy(image, kind); + case Kind.L8: return Copy(image, kind); + case Kind.L16: return Copy(image, kind); + case Kind.La16: return Copy(image, kind); + case Kind.La32: return Copy(image, kind); + case Kind.A8: return Copy(image, kind); + case Kind.Rgb48: return Copy(image, kind); + case Kind.Rgba64: return Copy(image, kind); + default: return Copy(image, kind); + } + } + + private static E.Image Copy(IS.Image source, Kind kind) where TE : unmanaged, E.IPixel + { + EnsureSameLayout(Unsafe.SizeOf(), source); + int width = source.Width, height = source.Height; + var frames = new List(source.Frames.Count); + var delays = new List(source.Frames.Count); + for (int f = 0; f < source.Frames.Count; f++) + { + TE[] pixels = E.PixelBuffer.Allocate(width, height); + CopyFrame(source, f, kind, MemoryMarshal.AsBytes(pixels.AsSpan())); + frames.Add(pixels); + delays.Add(IS.MetadataExtensions.GetGifMetadata(source.Frames[f].Metadata).FrameDelay); + } + + var metadata = new E.ImageMetadata + { + HorizontalResolution = source.Metadata.HorizontalResolution, + VerticalResolution = source.Metadata.VerticalResolution, + ResolutionUnits = (E.PixelResolutionUnit)(byte)source.Metadata.ResolutionUnits, + }; + if (frames.Count > 1) + { + metadata.FrameDelays = delays; + } + + return new E.Image(width, height, frames, metadata); + } + + private static void CopyFrame(IS.Image image, int frame, Kind kind, Span destination) + { + switch (kind) + { + case Kind.Rgba32: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Bgra32: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Abgr32: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Argb32: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Rgb24: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Bgr24: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.L8: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.L16: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.La16: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.La32: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.A8: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Rgb48: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + case Kind.Rgba64: ((IS.Image)image).Frames[frame].CopyPixelDataTo(destination); break; + default: throw new NotSupportedException($"Unsupported pixel format {kind}."); + } + } + + // ---- helpers -------------------------------------------------------------------------------------- + + private static Kind KindOf(IS.Image image) => image switch + { + IS.Image => Kind.Rgba32, + IS.Image => Kind.Bgra32, + IS.Image => Kind.Abgr32, + IS.Image => Kind.Argb32, + IS.Image => Kind.Rgb24, + IS.Image => Kind.Bgr24, + IS.Image => Kind.L8, + IS.Image => Kind.L16, + IS.Image => Kind.La16, + IS.Image => Kind.La32, + IS.Image => Kind.A8, + IS.Image => Kind.Rgb48, + IS.Image => Kind.Rgba64, + _ => Kind.Other, + }; + + private static Kind KindOf(E.Image image) => image switch + { + E.Image => Kind.Rgba32, + E.Image => Kind.Bgra32, + E.Image => Kind.Abgr32, + E.Image => Kind.Argb32, + E.Image => Kind.Rgb24, + E.Image => Kind.Bgr24, + E.Image => Kind.L8, + E.Image => Kind.L16, + E.Image => Kind.La16, + E.Image => Kind.La32, + E.Image => Kind.A8, + E.Image => Kind.Rgb48, + E.Image => Kind.Rgba64, + _ => Kind.Other, + }; + + private static void EnsureSameLayout(int enginePixelSize, IS.Image image) + { + if (image.PixelType.BitsPerPixel != enginePixelSize * 8) + { + throw new InvalidOperationException($"The engine pixel ({enginePixelSize} bytes) and {image.GetType().FullName} do not share a pixel layout."); + } + } + } +} +#endif diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpLoader.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpLoader.cs index 472e103e..1bb0fa3b 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpLoader.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/ImageSharpLoader.cs @@ -1,6 +1,13 @@ -// .NET Framework has no SixLabors.ImageSharp dependency (see SkiaEngine/), so this ImageSharp-typed API -// exists only on the other targets. AnyBitmap uses SkiaEngine.ImageSharpLoader there instead. -#if !NETFRAMEWORK +// On .NET Framework, SixLabors.ImageSharp is a compile-time-only reference (not a package dependency): this class +// is available there for callers that reference ImageSharp 2.x themselves, and loads it only when called. +// AnyBitmap itself never uses it on .NET Framework (it decodes with SkiaEngine.EngineLoader). +// +// The IPixel constraint of the generic Load overloads would make the .NET Framework type loader +// resolve SixLabors.ImageSharp as soon as this type is loaded (so without ImageSharp installed, Assembly.GetTypes() +// on this assembly would throw ReflectionTypeLoadException). The net462 build therefore removes that constraint +// from the compiled assembly, together with the cast in Load(byte[]) (see LoadAs), and signs it again +// (..\build\StripImageSharpConstraints\Program.cs). The build fails if any other generic code in this assembly is +// constrained to an ImageSharp type, so keep such code out of the .NET Framework build. using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System; @@ -17,6 +24,8 @@ namespace IronSoftware.Drawing /// data can hold is rejected, because ImageSharp 2.x loops on it without making progress /// (CVE-2026-106116, GHSA-wmxv-xphr-5c9g). On .NET 6 and .NET 8 the referenced ImageSharp versions /// are patched and these methods behave exactly like . + /// On .NET Framework, reference SixLabors.ImageSharp 2.x in your project to use this class (it is not a + /// dependency of this package there). /// public static class ImageSharpLoader { @@ -42,9 +51,54 @@ public static Image Load(byte[] data) public static Image Load(byte[] data) where TPixel : unmanaged, IPixel { ThrowIfUnsafe(data); +#if NETFRAMEWORK + // The net462 build strips the IPixel constraint from this method (see the top of this file), and + // the .NET Framework JIT then rejects a direct Image.Load call (VerificationException): it checks + // calls against the declared constraints. Calling it through reflection checks the actual type instead. + // The build also removes this cast (the JIT would reject Image the same way): keep it directly + // on the LoadAs call, which is how the build finds it. + return (Image)LoadAs(typeof(TPixel), data); +#else return Image.Load(data); +#endif } +#if NETFRAMEWORK + private static System.Reflection.MethodInfo genericLoad; + + private static object LoadAs(Type pixelType, byte[] data) + { + System.Reflection.MethodInfo load = genericLoad; + if (load == null) + { + foreach (System.Reflection.MethodInfo method in typeof(Image).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)) + { + if (method.Name == nameof(Image.Load) && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1) + { + System.Reflection.ParameterInfo[] parameters = method.GetParameters(); + if (parameters.Length == 1 && parameters[0].ParameterType == typeof(byte[])) + { + load = method; + break; + } + } + } + + genericLoad = load ?? throw new MissingMethodException(typeof(Image).FullName, "Load(byte[])"); + } + + try + { + return load.MakeGenericMethod(pixelType).Invoke(null, new object[] { data }); + } + catch (System.Reflection.TargetInvocationException e) when (e.InnerException != null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); + throw; + } + } +#endif + /// /// Decodes an image from the current position of , like /// . The remaining stream content is read into memory first. @@ -142,4 +196,3 @@ ulong ReadUInt64(long position) } } } -#endif diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/IronSoftware.Drawing.Common.csproj b/IronSoftware.Drawing/IronSoftware.Drawing.Common/IronSoftware.Drawing.Common.csproj index edc1216c..74bc7a7d 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/IronSoftware.Drawing.Common.csproj +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/IronSoftware.Drawing.Common.csproj @@ -45,6 +45,12 @@ + + @@ -73,6 +79,25 @@ + + + $(MSBuildThisFileDirectory)..\build\StripImageSharpConstraints\StripImageSharpConstraints.csproj + $(MSBuildThisFileDirectory)..\build\StripImageSharpConstraints\bin\out\ + $(DOTNET_HOST_PATH) + dotnet + + + + + + + portable true diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Legacy/CropRectangle.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Legacy/CropRectangle.cs index 0332340d..5bc12f32 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Legacy/CropRectangle.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Legacy/CropRectangle.cs @@ -201,7 +201,6 @@ public static implicit operator SkiaSharp.SKRectI(CropRectangle cropRectangle) return SkiaSharp.SKRectI.Create(cropRectangle.X, cropRectangle.Y, cropRectangle.Width, cropRectangle.Height); } -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.Rectangle objects to . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.Rectangle as well. @@ -211,9 +210,7 @@ public static implicit operator CropRectangle(SixLabors.ImageSharp.Rectangle rec { return new CropRectangle(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to SixLabors.ImageSharp.Rectangle objects from . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.Rectangle as well. @@ -223,9 +220,7 @@ public static implicit operator SixLabors.ImageSharp.Rectangle(CropRectangle cro { return new SixLabors.ImageSharp.Rectangle(cropRectangle.X, cropRectangle.Y, cropRectangle.Width, cropRectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.RectangleF objects to . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -235,9 +230,7 @@ public static implicit operator CropRectangle(SixLabors.ImageSharp.RectangleF re { return new CropRectangle((int)rectangle.X, (int)rectangle.Y, (int)rectangle.Width, (int)rectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to SixLabors.ImageSharp.RectangleF objects from . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -247,7 +240,6 @@ public static implicit operator SixLabors.ImageSharp.RectangleF(CropRectangle cr { return new SixLabors.ImageSharp.RectangleF(cropRectangle.X, cropRectangle.Y, cropRectangle.Width, cropRectangle.Height); } -#endif /// /// Implicitly casts Microsoft.Maui.Graphics.Rect objects to . diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Point.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Point.cs index 77755c3b..a0a9caf9 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Point.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Point.cs @@ -40,7 +40,6 @@ public void Offset(int dx, int dy) #region Implicit Operators -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.Point objects to Point /// @@ -49,9 +48,7 @@ public static implicit operator Point(SixLabors.ImageSharp.Point point) { return new Point(point.X, point.Y); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts Point objects to SixLabors.ImageSharp.Point /// @@ -60,7 +57,6 @@ public static implicit operator SixLabors.ImageSharp.Point(Point point) { return new SixLabors.ImageSharp.Point(point.X, point.Y); } -#endif /// /// Implicitly casts System.Drawing.Point objects to . diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/PointF.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/PointF.cs index b559db15..710201ff 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/PointF.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/PointF.cs @@ -40,7 +40,6 @@ public void Offset(float dx, float dy) #region Implicit Operators -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.PointF objects to PointF /// @@ -49,9 +48,7 @@ public static implicit operator PointF(SixLabors.ImageSharp.PointF point) { return new PointF(point.X, point.Y); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts a PointF object to SixLabors.ImageSharp.PointF /// @@ -60,7 +57,6 @@ public static implicit operator SixLabors.ImageSharp.PointF(PointF point) { return new SixLabors.ImageSharp.PointF(point.X, point.Y); } -#endif /// /// Implicitly casts Microsoft.Maui.Graphics.Point objects to PointF diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Rectangle.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Rectangle.cs index a7f8fd3a..fe8c3456 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Rectangle.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Rectangle.cs @@ -231,7 +231,6 @@ public static implicit operator SkiaSharp.SKRectI(Rectangle Rectangle) return SkiaSharp.SKRectI.Create(Rectangle.X, Rectangle.Y, Rectangle.Width, Rectangle.Height); } -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.Rectangle objects to . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.Rectangle as well. @@ -241,9 +240,7 @@ public static implicit operator Rectangle(SixLabors.ImageSharp.Rectangle rectang { return new Rectangle(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to SixLabors.ImageSharp.Rectangle objects from . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.Rectangle as well. @@ -253,9 +250,7 @@ public static implicit operator SixLabors.ImageSharp.Rectangle(Rectangle Rectang { return new SixLabors.ImageSharp.Rectangle(Rectangle.X, Rectangle.Y, Rectangle.Width, Rectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.RectangleF objects to . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -265,9 +260,7 @@ public static implicit operator Rectangle(SixLabors.ImageSharp.RectangleF rectan { return new Rectangle((int)rectangle.X, (int)rectangle.Y, (int)rectangle.Width, (int)rectangle.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to SixLabors.ImageSharp.RectangleF objects from . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -277,7 +270,6 @@ public static implicit operator SixLabors.ImageSharp.RectangleF(Rectangle Rectan { return new SixLabors.ImageSharp.RectangleF(Rectangle.X, Rectangle.Y, Rectangle.Width, Rectangle.Height); } -#endif /// /// Implicitly casts Microsoft.Maui.Graphics.Rect objects to . diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/RectangleF.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/RectangleF.cs index 75faad2a..ead79fc6 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/RectangleF.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/RectangleF.cs @@ -200,7 +200,6 @@ public static implicit operator SkiaSharp.SKRect(RectangleF RectangleF) return SkiaSharp.SKRect.Create(RectangleF.X, RectangleF.Y, RectangleF.Width, RectangleF.Height); } -#if !NETFRAMEWORK /// /// Implicitly casts SixLabors.ImageSharp.RectangleF objects to . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -210,9 +209,7 @@ public static implicit operator RectangleF(SixLabors.ImageSharp.RectangleF Recta { return new RectangleF(RectangleF.X, RectangleF.Y, RectangleF.Width, RectangleF.Height); } -#endif -#if !NETFRAMEWORK /// /// Implicitly casts to SixLabors.ImageSharp.RectangleF objects from . /// When your .NET Class methods use as parameters and return types, you now automatically support SixLabors.ImageSharp.RectangleF as well. @@ -222,7 +219,6 @@ public static implicit operator SixLabors.ImageSharp.RectangleF(RectangleF Recta { return new SixLabors.ImageSharp.RectangleF(RectangleF.X, RectangleF.Y, RectangleF.Width, RectangleF.Height); } -#endif /// /// Implicitly casts Microsoft.Maui.Graphics.Rect objects to . diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Size.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Size.cs index e8dde467..488d71e3 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/Size.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/Size.cs @@ -195,7 +195,6 @@ public Size(Point point) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Size left, Size right) => !left.Equals(right); -#if !NETFRAMEWORK /// /// Convert a type to a type. /// @@ -204,9 +203,7 @@ public static implicit operator Size(SixLabors.ImageSharp.Size v) { return new Size(v.Width, v.Height); } -#endif -#if !NETFRAMEWORK /// /// Convert to a type. /// @@ -215,7 +212,6 @@ public static implicit operator SixLabors.ImageSharp.Size(Size v) { return new SixLabors.ImageSharp.Size(v.Width, v.Height); } -#endif /// /// Convert a type to a type. diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SizeF.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SizeF.cs index 1a09b564..0650543c 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SizeF.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SizeF.cs @@ -183,7 +183,6 @@ public static implicit operator System.Drawing.SizeF(SizeF v) return new System.Drawing.SizeF(v.Width, v.Height); } -#if !NETFRAMEWORK /// /// Convert a type to a type. /// @@ -192,9 +191,7 @@ public static implicit operator SizeF(SixLabors.ImageSharp.SizeF v) { return new SizeF(v.Width, v.Height); } -#endif -#if !NETFRAMEWORK /// /// Convert to a type. /// @@ -203,7 +200,6 @@ public static implicit operator SixLabors.ImageSharp.SizeF(SizeF v) { return new SixLabors.ImageSharp.SizeF(v.Width, v.Height); } -#endif /// /// Convert a type to a type. diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Encoders.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Encoders.cs index 746c8198..30b4edf2 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Encoders.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Encoders.cs @@ -244,6 +244,7 @@ public void Encode(Image image, Stream stream) Image => ((byte)0, 1, false), Image => ((byte)0, 1, true), Image => ((byte)4, 2, false), + Image => ((byte)4, 2, false), // like ImageSharp: grayscale (0) with the alpha channel Image => ((byte)4, 2, true), Image or Image => ((byte)2, 3, false), Image => ((byte)2, 3, true), diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/EngineLoader.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/EngineLoader.cs new file mode 100644 index 00000000..ad335d10 --- /dev/null +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/EngineLoader.cs @@ -0,0 +1,17 @@ +#if NETFRAMEWORK +namespace IronSoftware.Drawing.SkiaEngine +{ + /// + /// The decoder AnyBitmap uses on .NET Framework, in place of IronSoftware.Drawing.ImageSharpLoader on the other + /// targets, so AnyBitmap keeps one code path. (The public ImageSharpLoader also exists on .NET Framework, for + /// callers that reference SixLabors.ImageSharp themselves; AnyBitmap must not use it, or every load would need ImageSharp.) TIFF goes through BitMiracle.LibTiff and everything else through SkiaSharp, neither of which + /// has ImageSharp 2.x's BigTIFF directory loop (CVE-2026-106116). + /// + internal static class EngineLoader + { + public static Image Load(byte[] data) => Image.Load(data); + + public static Image Load(byte[] data) where TPixel : unmanaged, IPixel => Image.Load(data); + } +} +#endif diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Image.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Image.cs index e7bc7625..4b604881 100644 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Image.cs +++ b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/Image.cs @@ -194,6 +194,9 @@ internal Image(int width, int height, List frames, ImageMetadata metad internal override int FrameCount => _frames.Count; internal TPixel[] RootPixels => _frames[0]; + /// The raw pixels of one frame (not a copy). + internal TPixel[] GetFramePixels(int index) => _frames[index]; + public TPixel this[int x, int y] { get => _frames[0][(y * _width) + x]; diff --git a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/ImageSharpLoader.cs b/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/ImageSharpLoader.cs deleted file mode 100644 index 3e5b85c6..00000000 --- a/IronSoftware.Drawing/IronSoftware.Drawing.Common/SkiaEngine/ImageSharpLoader.cs +++ /dev/null @@ -1,16 +0,0 @@ -#if NETFRAMEWORK -namespace IronSoftware.Drawing.SkiaEngine -{ - /// - /// .NET Framework counterpart of the public IronSoftware.Drawing.ImageSharpLoader, so AnyBitmap keeps one - /// code path. TIFF goes through BitMiracle.LibTiff and everything else through SkiaSharp, neither of which - /// has ImageSharp 2.x's BigTIFF directory loop (CVE-2026-106116). - /// - internal static class ImageSharpLoader - { - public static Image Load(byte[] data) => Image.Load(data); - - public static Image Load(byte[] data) where TPixel : unmanaged, IPixel => Image.Load(data); - } -} -#endif diff --git a/IronSoftware.Drawing/build/StripImageSharpConstraints/Program.cs b/IronSoftware.Drawing/build/StripImageSharpConstraints/Program.cs new file mode 100644 index 00000000..5b77ac44 --- /dev/null +++ b/IronSoftware.Drawing/build/StripImageSharpConstraints/Program.cs @@ -0,0 +1,427 @@ +// Build-time tool, run by IronSoftware.Drawing.Common.csproj on the net462 build only. +// +// Why: on .NET Framework, SixLabors.ImageSharp is a compile-time-only reference of IronSoftware.Drawing.Common. +// The public ImageSharpLoader.Load overloads are declared "where TPixel : unmanaged, IPixel", and +// the .NET Framework type loader resolves the types in generic-parameter constraints when it loads a type. So +// without ImageSharp installed, loading ImageSharpLoader (and so Assembly.GetTypes() on this assembly) would throw. +// Leaving the overloads out instead breaks binary compatibility: libraries compiled against the netstandard2.0 +// build call them and would get MissingMethodException. +// +// Constraints are not part of a method's signature: callers bind by name, generic arity, parameter types and +// return type. So this tool removes the ImageSharp interface constraint from those overloads in the compiled +// assembly (it now points at System.Object, which constrains nothing), keeps the "unmanaged" (value type) +// constraint, and strong-name signs the assembly again with the project's key. The type then loads without +// ImageSharp, and the overloads work exactly as before when the caller has ImageSharp: the runtime still checks +// ImageSharp's own constraints when Image and Image.Load are instantiated. +// +// Safety checks, each of which fails the build: +// - re-signing the untouched assembly must reproduce the compiler's strong-name signature byte for byte; +// - no other generic parameter in the assembly may have an ImageSharp constraint (it would break type loading); +// - nothing may be left to strip once the assembly has been processed (the tool is idempotent). +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using System.Security.Cryptography; + +// Usage: StripImageSharpConstraints +public static class StripImageSharpConstraints +{ + private const string ImageSharpAssembly = "SixLabors.ImageSharp"; + private const string LoaderNamespace = "IronSoftware.Drawing"; + private const string LoaderType = "ImageSharpLoader"; + + public static int Main(string[] args) + { + if (args.Length != 2) + { + Console.Error.WriteLine("usage: StripImageSharpConstraints "); + return 2; + } + + string assemblyPath = args[0]; + try + { + byte[] image = File.ReadAllBytes(assemblyPath); + int stripped = ConstraintStripper.Strip(image, File.ReadAllBytes(args[1])); + if (stripped > 0) + { + File.WriteAllBytes(assemblyPath, image); + } + + Console.WriteLine("StripImageSharpConstraints: {0}: patched {1} ImageSharp constraint(s) and cast(s) in {2}.Load{3}.", Path.GetFileName(assemblyPath), stripped, LoaderType, stripped > 0 ? " and re-signed" : " (already processed)"); + return 0; + } + catch (Exception e) + { + // MSBuild's canonical error format, so the Exec task reports it as a build error. + Console.Error.WriteLine("{0}: error ISD0001: StripImageSharpConstraints: {1}", assemblyPath, e.Message); + return 1; + } + } + + private static class ConstraintStripper + { + // Patches image in place and returns the number of constraints removed (0: nothing written). + public static int Strip(byte[] image, byte[] keyBlob) + { + var patches = new List(); // file offsets of the Constraint column to point at System.Object + int objectToken; + int codedIndexSize; + SigningLayout layout; + List casts; // file offsets of "castclass Image" right before the final "ret" + + using (var pe = new PEReader(new MemoryStream(image, false))) + { + MetadataReader md = pe.GetMetadataReader(); + PEHeaders headers = pe.PEHeaders; + layout = SigningLayout.Read(md, headers); + + objectToken = FindSystemObject(md); + int ownerSize = md.GetTableRowCount(TableIndex.GenericParam) > ushort.MaxValue ? 4 : 2; + codedIndexSize = md.GetTableRowSize(TableIndex.GenericParamConstraint) - ownerSize; + int tableStart = headers.MetadataStartOffset + md.GetTableMetadataOffset(TableIndex.GenericParamConstraint); + int rowSize = md.GetTableRowSize(TableIndex.GenericParamConstraint); + + foreach (GenericParameterConstraintHandle handle in AllConstraints(md)) + { + GenericParameterConstraint constraint = md.GetGenericParameterConstraint(handle); + if (!IsImageSharpType(md, constraint.Type)) + { + continue; + } + + GenericParameter parameter = md.GetGenericParameter(constraint.Parameter); + if (!IsLoaderMethod(md, parameter.Parent)) + { + throw new InvalidOperationException(string.Format( + "generic parameter '{0}' of {1} has a SixLabors.ImageSharp constraint. On .NET Framework that makes the type fail to load without ImageSharp; use a non-generic helper instead.", + md.GetString(parameter.Name), Describe(md, parameter.Parent))); + } + + int row = MetadataTokens.GetRowNumber(handle); + patches.Add(tableStart + ((row - 1) * rowSize) + ownerSize); + } + + casts = FindReturnCasts(pe, md); + if (patches.Count > 0 && casts.Count == 0) + { + throw new InvalidOperationException(LoaderType + ".Load(byte[]) must return \"(Image)LoadAs(...)\" on .NET Framework (call LoadAs + castclass), see ImageSharpLoader.cs."); + } + + // The compiler's signature must be reproducible, otherwise the hashing below is not what the + // runtime verifies and re-signing would produce an assembly that fails strong-name validation. + byte[] expected = Sign(image, keyBlob, layout); + if (!expected.SequenceEqual(image.Skip(layout.SignatureOffset).Take(layout.SignatureSize))) + { + throw new InvalidOperationException("re-signing the unmodified assembly does not reproduce its strong-name signature (wrong key file?)."); + } + } + + if (patches.Count == 0 && casts.Count == 0) + { + return 0; + } + + // Without the constraint, the .NET Framework JIT rejects "castclass Image" (TypeLoadException: + // TPixel violates the constraint of Image), and C# cannot return the object without it. The + // reflection call already returns an Image, so the cast is replaced with nops. + foreach (int offset in casts) + { + for (int i = 0; i < 5; i++) + { + image[offset + i] = 0x00; // nop + } + } + + // TypeDefOrRef coded index: (row << 2) | 1 for a TypeRef. + uint coded = ((uint)MetadataTokens.GetRowNumber(MetadataTokens.TypeReferenceHandle(objectToken)) << 2) | 1; + foreach (int offset in patches) + { + if (codedIndexSize == 2) + { + if (coded > ushort.MaxValue) + { + throw new InvalidOperationException("System.Object TypeRef index does not fit the coded index."); + } + + image[offset] = (byte)coded; + image[offset + 1] = (byte)(coded >> 8); + } + else + { + image[offset] = (byte)coded; + image[offset + 1] = (byte)(coded >> 8); + image[offset + 2] = (byte)(coded >> 16); + image[offset + 3] = (byte)(coded >> 24); + } + } + + byte[] signature = Sign(image, keyBlob, layout); + Buffer.BlockCopy(signature, 0, image, layout.SignatureOffset, layout.SignatureSize); + + using (var pe = new PEReader(new MemoryStream(image, false))) + { + MetadataReader md = pe.GetMetadataReader(); + if (AllConstraints(md).Any(h => IsImageSharpType(md, md.GetGenericParameterConstraint(h).Type)) || FindReturnCasts(pe, md).Count > 0) + { + throw new InvalidOperationException("ImageSharp constraints or casts remain after patching."); + } + } + + return patches.Count + casts.Count; + } + + // Offsets of the "castclass " that follows "call LoadAs" in the generic Load methods. + private static List FindReturnCasts(PEReader pe, MetadataReader md) + { + var offsets = new List(); + int loadAsToken = FindLoadAs(md); + foreach (MethodDefinitionHandle handle in md.MethodDefinitions) + { + MethodDefinition method = md.GetMethodDefinition(handle); + if (loadAsToken == 0 || method.RelativeVirtualAddress == 0 || method.GetGenericParameters().Count != 1 || !IsLoaderMethod(md, handle)) + { + continue; + } + + int bodyOffset = RvaToOffset(pe.PEHeaders, method.RelativeVirtualAddress); + MethodBodyBlock body = pe.GetMethodBody(method.RelativeVirtualAddress); + int headerSize = (pe.GetEntireImage().GetContent()[bodyOffset] & 3) == 2 ? 1 : 12; // tiny or fat header + byte[] il = body.GetILBytes(); + + // "call LoadAs" immediately followed by "castclass ". The call token pins + // the match to the one cast this tool is meant to remove, in Debug and Release IL alike. + for (int i = 0; i + 10 <= il.Length; i++) + { + if (il[i] != 0x28 || il[i + 5] != 0x74 || BitConverter.ToInt32(il, i + 1) != loadAsToken) + { + continue; + } + + EntityHandle type = MetadataTokens.EntityHandle(BitConverter.ToInt32(il, i + 6)); + if (type.Kind == HandleKind.TypeSpecification && IsImageSharpType(md, type)) + { + offsets.Add(bodyOffset + headerSize + i + 5); + } + } + } + + return offsets; + } + + private static int FindLoadAs(MetadataReader md) + { + foreach (MethodDefinitionHandle handle in md.MethodDefinitions) + { + MethodDefinition method = md.GetMethodDefinition(handle); + TypeDefinition type = md.GetTypeDefinition(method.GetDeclaringType()); + if (md.StringComparer.Equals(method.Name, "LoadAs") && md.StringComparer.Equals(type.Name, LoaderType) && md.StringComparer.Equals(type.Namespace, LoaderNamespace)) + { + return MetadataTokens.GetToken(handle); + } + } + + return 0; + } + + private static int RvaToOffset(PEHeaders headers, int rva) + { + foreach (SectionHeader section in headers.SectionHeaders) + { + if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.SizeOfRawData) + { + return rva - section.VirtualAddress + section.PointerToRawData; + } + } + + throw new InvalidOperationException(string.Format("RVA 0x{0:X} is outside every section.", rva)); + } + + private static IEnumerable AllConstraints(MetadataReader md) + { + int count = md.GetTableRowCount(TableIndex.GenericParamConstraint); + for (int row = 1; row <= count; row++) + { + yield return MetadataTokens.GenericParameterConstraintHandle(row); + } + } + + private static int FindSystemObject(MetadataReader md) + { + foreach (TypeReferenceHandle handle in md.TypeReferences) + { + TypeReference type = md.GetTypeReference(handle); + if (md.StringComparer.Equals(type.Name, "Object") && md.StringComparer.Equals(type.Namespace, "System") + && type.ResolutionScope.Kind == HandleKind.AssemblyReference + && md.StringComparer.Equals(md.GetAssemblyReference((AssemblyReferenceHandle)type.ResolutionScope).Name, "mscorlib")) + { + return MetadataTokens.GetToken(handle); + } + } + + throw new InvalidOperationException("no TypeRef to [mscorlib]System.Object found."); + } + + private static bool IsLoaderMethod(MetadataReader md, EntityHandle parent) + { + if (parent.Kind != HandleKind.MethodDefinition) + { + return false; + } + + MethodDefinition method = md.GetMethodDefinition((MethodDefinitionHandle)parent); + TypeDefinition type = md.GetTypeDefinition(method.GetDeclaringType()); + return md.StringComparer.Equals(method.Name, "Load") + && md.StringComparer.Equals(type.Name, LoaderType) + && md.StringComparer.Equals(type.Namespace, LoaderNamespace); + } + + private static string Describe(MetadataReader md, EntityHandle parent) + { + if (parent.Kind == HandleKind.MethodDefinition) + { + MethodDefinition method = md.GetMethodDefinition((MethodDefinitionHandle)parent); + TypeDefinition type = md.GetTypeDefinition(method.GetDeclaringType()); + return md.GetString(type.Namespace) + "." + md.GetString(type.Name) + "." + md.GetString(method.Name); + } + + TypeDefinition definition = md.GetTypeDefinition((TypeDefinitionHandle)parent); + return md.GetString(definition.Namespace) + "." + md.GetString(definition.Name); + } + + // True when the constraint type is, or is an instantiation of, a type from SixLabors.ImageSharp. + private static bool IsImageSharpType(MetadataReader md, EntityHandle type) + { + if (type.Kind == HandleKind.TypeSpecification) + { + BlobReader blob = md.GetBlobReader(md.GetTypeSpecification((TypeSpecificationHandle)type).Signature); + if (blob.ReadSignatureTypeCode() != SignatureTypeCode.GenericTypeInstance) + { + return false; + } + + blob.ReadSignatureTypeCode(); // CLASS or VALUETYPE + type = blob.ReadTypeHandle(); + } + + if (type.Kind != HandleKind.TypeReference) + { + return false; + } + + EntityHandle scope = md.GetTypeReference((TypeReferenceHandle)type).ResolutionScope; + while (scope.Kind == HandleKind.TypeReference) + { + scope = md.GetTypeReference((TypeReferenceHandle)scope).ResolutionScope; + } + + return scope.Kind == HandleKind.AssemblyReference + && md.StringComparer.Equals(md.GetAssemblyReference((AssemblyReferenceHandle)scope).Name, ImageSharpAssembly); + } + + private sealed class SigningLayout + { + public int ChecksumOffset; + public int SecurityDirectoryOffset; + public int HeadersEnd; // end of the section table (the headers' alignment padding is not signed) + public int SectionsStart; // SizeOfHeaders + public int SignatureOffset; + public int SignatureSize; + public HashAlgorithmName HashAlgorithm; + + public static SigningLayout Read(MetadataReader md, PEHeaders headers) + { + int signatureOffset; + if ((headers.CorHeader.Flags & CorFlags.StrongNameSigned) == 0 || !headers.TryGetDirectoryOffset(headers.CorHeader.StrongNameSignatureDirectory, out signatureOffset)) + { + throw new InvalidOperationException("the assembly is not strong-name signed."); + } + + // The signature hash algorithm is the one in the public key blob (PUBLICKEYBLOB header: SigAlgID, HashAlgID, ...). + byte[] publicKey = md.GetBlobBytes(md.GetAssemblyDefinition().PublicKey); + uint hashAlgId = publicKey.Length >= 12 ? BitConverter.ToUInt32(publicKey, 4) : 0; + HashAlgorithmName hashAlgorithm; + switch (hashAlgId) + { + case 0x8004: hashAlgorithm = HashAlgorithmName.SHA1; break; + case 0x800C: hashAlgorithm = HashAlgorithmName.SHA256; break; + case 0x800D: hashAlgorithm = HashAlgorithmName.SHA384; break; + case 0x800E: hashAlgorithm = HashAlgorithmName.SHA512; break; + default: throw new InvalidOperationException(string.Format("unsupported strong-name hash algorithm 0x{0:X}.", hashAlgId)); + } + + return new SigningLayout + { + ChecksumOffset = headers.PEHeaderStartOffset + 64, + SecurityDirectoryOffset = headers.PEHeaderStartOffset + (headers.PEHeader.Magic == PEMagic.PE32Plus ? 112 : 96) + (4 * 8), + HeadersEnd = headers.PEHeaderStartOffset + headers.CoffHeader.SizeOfOptionalHeader + (headers.SectionHeaders.Length * 40), + SectionsStart = headers.PEHeader.SizeOfHeaders, + SignatureOffset = signatureOffset, + SignatureSize = headers.CorHeader.StrongNameSignatureDirectory.Size, + HashAlgorithm = hashAlgorithm, + }; + } + } + + // Strong-name signature, as the C# compiler computes it: the hash of the PE headers without their alignment + // padding and with the checksum and security (Authenticode) directory entry zeroed, followed by the section + // data without the signature blob; signed with RSA PKCS#1 and stored little-endian. + private static byte[] Sign(byte[] image, byte[] keyBlob, SigningLayout layout) + { + if (layout.SignatureOffset < layout.SectionsStart || layout.SignatureOffset + layout.SignatureSize > image.Length) + { + throw new InvalidOperationException("unexpected strong-name signature location."); + } + + byte[] peHeaders = new byte[layout.HeadersEnd]; + Buffer.BlockCopy(image, 0, peHeaders, 0, peHeaders.Length); + Array.Clear(peHeaders, layout.ChecksumOffset, 4); + Array.Clear(peHeaders, layout.SecurityDirectoryOffset, 8); + HashAlgorithmName name = layout.HashAlgorithm; + + byte[] hash; + using (IncrementalHash hasher = IncrementalHash.CreateHash(name)) + { + hasher.AppendData(peHeaders); + hasher.AppendData(image, layout.SectionsStart, layout.SignatureOffset - layout.SectionsStart); + int afterSignature = layout.SignatureOffset + layout.SignatureSize; + hasher.AppendData(image, afterSignature, image.Length - afterSignature); + hash = hasher.GetHashAndReset(); + } + + byte[] signature; + RSAParameters key; + using (var csp = new RSACryptoServiceProvider()) + { + // The .snk is a CryptoAPI private key blob for the signature key; read it here and sign with a + // plain RSA object (signing with the CSP itself fails for signature keys: "Keyset does not exist"). + csp.ImportCspBlob(keyBlob); + if (csp.PublicOnly) + { + throw new InvalidOperationException("the key file has no private key."); + } + + key = csp.ExportParameters(true); + } + + using (RSA rsa = RSA.Create()) + { + rsa.ImportParameters(key); + signature = rsa.SignHash(hash, name, RSASignaturePadding.Pkcs1); + } + + if (signature.Length != layout.SignatureSize) + { + throw new InvalidOperationException("the signature size does not match the reserved space."); + } + + Array.Reverse(signature); + return signature; + } + } +} diff --git a/IronSoftware.Drawing/build/StripImageSharpConstraints/StripImageSharpConstraints.csproj b/IronSoftware.Drawing/build/StripImageSharpConstraints/StripImageSharpConstraints.csproj new file mode 100644 index 00000000..1d1d13ce --- /dev/null +++ b/IronSoftware.Drawing/build/StripImageSharpConstraints/StripImageSharpConstraints.csproj @@ -0,0 +1,19 @@ + + + + + Exe + net$(BundledNETCoreAppTargetFrameworkVersion) + false + latest + disable + disable + false + false + + + diff --git a/NuGet/IronSoftware.Drawing.nuspec b/NuGet/IronSoftware.Drawing.nuspec index 8363cb1e..372a7593 100644 --- a/NuGet/IronSoftware.Drawing.nuspec +++ b/NuGet/IronSoftware.Drawing.nuspec @@ -43,7 +43,7 @@ For general support and technical inquiries, please email us at: support@ironsof 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 - On .NET Framework, SVG loading uses Svg.Skia 5.2.3 instead of SkiaSharp.Svg 1.60 (which does not work with SkiaSharp 4); install Svg.Skia 5.x (tested with 5.2.3) to load SVG files - All targets: HorizontalResolution/VerticalResolution now round pixels-per-metre (PNG, BMP) and pixels-per-centimetre (TIFF) values to the nearest DPI. Previously PNG values were rounded up and multi-page TIFF values were truncated, and multi-page TIFFs ignored ResolutionUnit=cm. For example, a 72 DPI PNG (2835 px/m) now reports 72 instead of 73, and a 96 DPI multi-page TIFF stored per centimetre reports 96 instead of 37. Code that compared these values with the old results may see different numbers. Features @@ -51,7 +51,7 @@ Features - Updated SixLabors.ImageSharp to 3.2.0 (Drawing 2.2.0) for .NET 6 and 4.1.3 (Drawing 3.1.3) for .NET 8. .NET Standard 2.0 stays on 2.1.13. Security - .NET Standard 2.0: AnyBitmap now rejects malformed BigTIFF files that make ImageSharp 2.1.13 loop forever (CVE-2026-106116). .NET Framework decodes TIFF with BitMiracle.LibTiff.NET and is not affected. -- Added ImageSharpLoader (.NET Standard 2.0, .NET 6, .NET 8), a drop-in replacement for SixLabors.ImageSharp Image.Load that applies the same check. Use it instead of Image.Load on untrusted data. It is not available on .NET Framework, which has no ImageSharp dependency. +- Added ImageSharpLoader, a drop-in replacement for SixLabors.ImageSharp Image.Load that applies the same check. Use it instead of Image.Load on untrusted data. On .NET Framework it needs SixLabors.ImageSharp 2.x referenced by the app. Dependencies - .NET Framework: SkiaSharp 4.153.3 and SixLabors.Fonts 1.0.0 are now declared dependencies; SixLabors.ImageSharp and SixLabors.ImageSharp.Drawing are no longer required - .NET Standard 2.0 / .NET Framework: System.Memory 4.6.3, System.Buffers 4.6.1, System.Numerics.Vectors 4.6.1 and System.Runtime.CompilerServices.Unsafe 6.1.2 are now declared dependencies. .NET Framework apps need binding redirects to System.Memory 4.0.5.0, System.Buffers 4.0.5.0, System.Numerics.Vectors 4.1.6.0 and System.Runtime.CompilerServices.Unsafe 6.0.3.0; SDK-style and PackageReference projects generate these automatically.