feat(windows): add WIC decoder provider and codec inventory
WicDecoderProvider decodes through a pull chain (decoder, Fant scaler to MaxLongEdge, format converter) read in bounded row bands. Integer sources are requested as 64bppRGBA and linearised with the exact sRGB EOTF (Linear16); float/fixed sources as 128bppRGBAFloat (scRGB, already linear). The Exif orientation (photo policy, then raw IFD queries) is applied while de-interleaving instead of through IWICBitmapFlipRotator, which Microsoft documents as quadratic over scanline decoders. CodecInventory enumerates installed decoders (CreateComponentEnumerator), probes HEVC/AV1 decoders with MFTEnumEx and identifies the Raw Image Extension by package family, since it shares the in-box RAW codec's CLSID. It maps every ImageFileFormat to its decoder, native flag and the Store extensions (product ids, ms-windows-store links) that would unlock it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
15 files changed
+1555
No files matched your search
@@ -0,0 +1,145 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Codecs;
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Codecs;
|
||||
|
||||
public sealed class CodecInventoryTests
|
||||
{
|
||||
private static readonly WicDecoderInfo Jpeg = Decoder("JPEG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".jpeg,.jpe,.jpg,.jfif,.exif");
|
||||
private static readonly WicDecoderInfo InBoxDng = Decoder("DNG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".dng");
|
||||
private static readonly WicDecoderInfo Raw = Decoder("Microsoft Raw Image Decoder", WicGuids.RawDecoder, WicGuids.VendorMicrosoft, ".arw,.cr2,.cr3,.dng,.nef,.raf");
|
||||
private static readonly WicDecoderInfo Heif = Decoder("HEIF Decoder", WicGuids.HeifDecoder, WicGuids.VendorMicrosoft, ".heic,.heif,.hif");
|
||||
private static readonly WicDecoderInfo Webp = Decoder("WebP Decoder", WicGuids.WebpDecoder, WicGuids.VendorMicrosoft, ".webp");
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void DetectFindsTheBuiltInDecoders()
|
||||
{
|
||||
var inventory = CodecInventory.Detect();
|
||||
Assert.NotEmpty(inventory.Decoders);
|
||||
foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff })
|
||||
{
|
||||
var support = inventory.For(format);
|
||||
Assert.True(support.IsNative, $"{format} should decode natively through WIC");
|
||||
var decoder = Assert.NotNull(support.Decoder);
|
||||
Assert.False(string.IsNullOrWhiteSpace(decoder.FriendlyName), $"{format} decoder has no name");
|
||||
Assert.NotEqual(Guid.Empty, decoder.ContainerFormat);
|
||||
Assert.Empty(support.MissingExtensions);
|
||||
}
|
||||
Assert.Equal(ImageFormatInfo.Known.Count, inventory.Formats.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RawNeedsTheRawImageExtension()
|
||||
{
|
||||
var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: false)]);
|
||||
var dng = inventory.For(ImageFileFormat.Dng);
|
||||
Assert.False(dng.IsNative);
|
||||
Assert.Equal<string?>("DNG Decoder", dng.Decoder?.FriendlyName);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.RawImage)], dng.MissingExtensions);
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Cr3));
|
||||
Assert.Contains(StoreExtension.Get(StoreExtensionKind.RawImage), inventory.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RawIsNativeThroughTheExtension()
|
||||
{
|
||||
var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: true)]);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Dng));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.RawImage, inventory.For(ImageFileFormat.Dng).Decoder?.Extension);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Cr3));
|
||||
// Installed but without this extension registered: nothing to install, still not native.
|
||||
var gpr = inventory.For(ImageFileFormat.Gpr);
|
||||
Assert.False(gpr.IsNative);
|
||||
Assert.Empty(gpr.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeifNeedsAnHevcDecoder()
|
||||
{
|
||||
var withoutHevc = Inventory([Jpeg, Classified(Heif)]).For(ImageFileFormat.Heif);
|
||||
Assert.False(withoutHevc.IsNative);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.HevcVideo)], withoutHevc.MissingExtensions);
|
||||
|
||||
Assert.True(Inventory([Jpeg, Classified(Heif)], hevc: true).IsNative(ImageFileFormat.Heif));
|
||||
|
||||
var nothing = Inventory([Jpeg]).For(ImageFileFormat.Heif);
|
||||
Assert.SequenceEqual(
|
||||
[StoreExtension.Get(StoreExtensionKind.HeifImage), StoreExtension.Get(StoreExtensionKind.HevcVideo)],
|
||||
nothing.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AvifUsesTheHeifDecoderWithAnAv1Decoder()
|
||||
{
|
||||
var withoutAv1 = Inventory([Classified(Heif)], hevc: true).For(ImageFileFormat.Avif);
|
||||
Assert.False(withoutAv1.IsNative);
|
||||
Assert.Equal<string?>("HEIF Decoder", withoutAv1.Decoder?.FriendlyName);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.Av1Video)], withoutAv1.MissingExtensions);
|
||||
|
||||
Assert.True(Inventory([Classified(Heif)], av1: true).IsNative(ImageFileFormat.Avif));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WebpNeedsTheWebpExtension()
|
||||
{
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.WebpImage)], Inventory([Jpeg]).For(ImageFileFormat.WebP).MissingExtensions);
|
||||
Assert.True(Inventory([Jpeg, Classified(Webp)]).IsNative(ImageFileFormat.WebP));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuiltInFormatsNeverAskForExtensions()
|
||||
{
|
||||
var inventory = Inventory([Jpeg]);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Jpeg));
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Png));
|
||||
Assert.Empty(inventory.For(ImageFileFormat.Png).MissingExtensions);
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Unknown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClassificationUsesClsidPackageAndVendor()
|
||||
{
|
||||
Assert.Null(CodecInventory.Classify(Raw, rawExtensionInstalled: false));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.RawImage, CodecInventory.Classify(Raw, rawExtensionInstalled: true));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.HeifImage, CodecInventory.Classify(Heif, false));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.WebpImage, CodecInventory.Classify(Webp, false));
|
||||
var avif = Decoder("AVIF Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoft, ".avif");
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.Av1Video, CodecInventory.Classify(avif, false));
|
||||
var thirdParty = Decoder("Other AVIF", Guid.NewGuid(), Guid.NewGuid(), ".avif");
|
||||
Assert.Null(CodecInventory.Classify(thirdParty, false));
|
||||
Assert.Null(CodecInventory.Classify(Jpeg, false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StoreLinksUseTheProductIds()
|
||||
{
|
||||
Assert.Equal(5, StoreExtension.All.Count);
|
||||
var raw = StoreExtension.Get(StoreExtensionKind.RawImage);
|
||||
Assert.Equal("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8", raw.StoreUri.AbsoluteUri);
|
||||
Assert.Equal("https://apps.microsoft.com/detail/9nctdw2w1bh8", raw.WebUri.AbsoluteUri);
|
||||
Assert.Equal("9PMMSR1CGPWG", StoreExtension.Get(StoreExtensionKind.HeifImage).ProductId);
|
||||
Assert.Equal("9NMZLZ57R3T7", StoreExtension.Get(StoreExtensionKind.HevcVideo).ProductId);
|
||||
Assert.Equal("9MVZQVXJBQ9V", StoreExtension.Get(StoreExtensionKind.Av1Video).ProductId);
|
||||
Assert.Equal("9PG2DK419DRG", StoreExtension.Get(StoreExtensionKind.WebpImage).ProductId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExtensionListsAreNormalised()
|
||||
{
|
||||
Assert.SequenceEqual(["jpg", "jpeg", "jfif"], WicDecoderInfo.ParseExtensions(".JPG, .jpeg;.jfif,,.jpg"));
|
||||
Assert.True(Jpeg.Handles(".JPG"));
|
||||
Assert.True(Jpeg.Handles("jfif"));
|
||||
Assert.False(Jpeg.Handles("png"));
|
||||
}
|
||||
|
||||
private static CodecInventory Inventory(WicDecoderInfo[] decoders, bool hevc = false, bool av1 = false) => new(decoders, hevc, av1);
|
||||
|
||||
private static WicDecoderInfo Classified(WicDecoderInfo decoder, bool rawExtensionInstalled = false) =>
|
||||
decoder with { Extension = CodecInventory.Classify(decoder, rawExtensionInstalled) };
|
||||
|
||||
private static WicDecoderInfo Decoder(string name, Guid clsid, Guid vendor, string extensions) =>
|
||||
new(name, clsid, Guid.NewGuid(), vendor, "1.0", WicDecoderInfo.ParseExtensions(extensions), null);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
public sealed class OrientationMapTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(2)]
|
||||
[Case(3)]
|
||||
[Case(4)]
|
||||
[Case(5)]
|
||||
[Case(6)]
|
||||
[Case(7)]
|
||||
[Case(8)]
|
||||
public void MatchesTheExifDefinition(int orientation)
|
||||
{
|
||||
const int width = 5, height = 3;
|
||||
var map = OrientationMap.Create(orientation, width, height);
|
||||
var swapped = OrientationMap.SwapsAxes(orientation);
|
||||
Assert.Equal(swapped ? height : width, map.Width);
|
||||
Assert.Equal(swapped ? width : height, map.Height);
|
||||
|
||||
var seen = new HashSet<int>();
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (dx, dy) = Reference(orientation, x, y, width, height);
|
||||
Assert.Equal((dy * map.Width) + dx, map.IndexOf(x, y), $"orientation {orientation}, pixel ({x},{y})");
|
||||
seen.Add(map.IndexOf(x, y));
|
||||
}
|
||||
}
|
||||
Assert.Equal(width * height, seen.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownValuesActAsIdentity() => Assert.Equal(OrientationMap.Create(1, 4, 2), OrientationMap.Create(0, 4, 2));
|
||||
|
||||
[Theory]
|
||||
[Case(4000u, 3000u, 1920, 1920u, 1440u)]
|
||||
[Case(400u, 100u, 100, 100u, 25u)]
|
||||
[Case(3000u, 4000u, 1000, 750u, 1000u)]
|
||||
[Case(640u, 480u, 0, 640u, 480u)]
|
||||
[Case(640u, 480u, 2000, 640u, 480u)]
|
||||
[Case(2u, 1000u, 10, 1u, 10u)]
|
||||
public void TargetSizeFitsTheLongEdge(uint width, uint height, int maxLongEdge, uint expectedWidth, uint expectedHeight)
|
||||
{
|
||||
var (w, h) = WicDecoderProvider.TargetSize(width, height, maxLongEdge);
|
||||
Assert.Equal(expectedWidth, w);
|
||||
Assert.Equal(expectedHeight, h);
|
||||
}
|
||||
|
||||
/// <summary>Displayed position of stored pixel (x, y), straight from the Exif 2.3 orientation table.</summary>
|
||||
private static (int X, int Y) Reference(int orientation, int x, int y, int w, int h) => orientation switch
|
||||
{
|
||||
2 => (w - 1 - x, y),
|
||||
3 => (w - 1 - x, h - 1 - y),
|
||||
4 => (x, h - 1 - y),
|
||||
5 => (y, x),
|
||||
6 => (h - 1 - y, x),
|
||||
7 => (h - 1 - y, w - 1 - x),
|
||||
8 => (y, w - 1 - x),
|
||||
_ => (x, y),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
[WindowsOnly]
|
||||
public sealed class WicDecoderProviderTests(TestContext context)
|
||||
{
|
||||
private static readonly Lazy<WicDecoderProvider> SharedProvider = new(() => new WicDecoderProvider());
|
||||
private static readonly double MidGrey = ColorSpace.SrgbToLinear(128 / 255.0);
|
||||
|
||||
private static WicDecoderProvider Provider => SharedProvider.Value;
|
||||
|
||||
[Test]
|
||||
public void BuiltInFormatsAreNative()
|
||||
{
|
||||
Assert.Equal("wic", Provider.Name);
|
||||
foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff, ImageFileFormat.Bmp, ImageFileFormat.Gif })
|
||||
Assert.Equal<DecodeTier?>(DecodeTier.Native, Provider.TierFor(format), format.ToString());
|
||||
Assert.Null(Provider.TierFor(ImageFileFormat.Unknown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PngMidGreyDecodesToLinearLight()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey.png");
|
||||
WicTestImages.WriteRgbPng(path, 64, 48, (_, _) => (128, 128, 128));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(DecodeTier.Native, image.Tier);
|
||||
Assert.Equal("wic", image.Decoder);
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(48, image.Pixels.Height);
|
||||
Assert.Equal(3, image.Pixels.Channels);
|
||||
Assert.Equal(64, image.SourceWidth);
|
||||
Assert.Equal(48, image.SourceHeight);
|
||||
AssertUniform(image.Pixels, MidGrey, 1e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PngChannelsKeepTheirOrder()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "red-blue.png");
|
||||
WicTestImages.WriteRgbPng(path, 32, 16, (x, _) => x < 16 ? ((byte)255, (byte)0, (byte)0) : ((byte)0, (byte)0, (byte)255));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
var p = image.Pixels;
|
||||
Assert.Approximately(1.0, p[0, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[1, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[2, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[0, 28, 8], 1e-4);
|
||||
Assert.Approximately(1.0, p[2, 28, 8], 1e-4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SixteenBitPngKeepsPrecision()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey16.png");
|
||||
WicTestImages.WriteGray16Png(path, 8, 8, 0x8000);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
AssertUniform(image.Pixels, ColorSpace.Linear16(0x8000), 1e-4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JpegMidGreyDecodesToLinearLight()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 48, (_, _) => 128);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(48, image.Pixels.Height);
|
||||
AssertUniform(image.Pixels, MidGrey, 1e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ScalingToMaxLongEdgeKeepsAspect()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "wide.png");
|
||||
WicTestImages.WriteRgbPng(path, 400, 100, (_, _) => (128, 128, 128));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, MaxLongEdge: 100)));
|
||||
Assert.Equal(100, image.Pixels.Width);
|
||||
Assert.Equal(25, image.Pixels.Height);
|
||||
Assert.Equal(400, image.SourceWidth);
|
||||
Assert.Equal(100, image.SourceHeight);
|
||||
AssertUniform(image.Pixels, MidGrey, 2e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Orientation6RotatesClockwise()
|
||||
{
|
||||
// Stored 64×32 with a white 16×16 block at the top-left; displayed 32×64 with the block at the top-right.
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(32, image.Pixels.Width);
|
||||
Assert.Equal(64, image.Pixels.Height);
|
||||
Assert.Equal(32, image.SourceWidth);
|
||||
Assert.Equal(64, image.SourceHeight);
|
||||
Assert.Greater(image.Pixels[1, 24, 8], 0.8);
|
||||
Assert.Less(image.Pixels[1, 8, 8], 0.05);
|
||||
Assert.Less(image.Pixels[1, 24, 40], 0.05);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrientationIsIgnoredWhenNotRequested()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, ApplyOrientation: false)));
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(32, image.Pixels.Height);
|
||||
Assert.Greater(image.Pixels[1, 8, 8], 0.8);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DecodesAFileAnotherProcessHasOpenForWriting()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "busy.png");
|
||||
WicTestImages.WriteRgbPng(path, 16, 16, (_, _) => (128, 128, 128));
|
||||
using var writer = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(16, image.Pixels.Width);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnrecognisedContentReturnsNull()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "noise.png");
|
||||
File.WriteAllBytes(path, Enumerable.Range(0, 4096).Select(i => (byte)(i * 37)).ToArray());
|
||||
Assert.Null(Provider.Decode(new DecodeRequest(path)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingFileThrowsFileNotFound()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "missing.png");
|
||||
Assert.Throws<FileNotFoundException>(() => Provider.Decode(new DecodeRequest(path)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForcedPreviewIsLeftToOtherProviders() =>
|
||||
Assert.Null(Provider.Decode(new DecodeRequest(Path.Combine(context.CreateTempDirectory(), "any.jpg"), ForcePreview: true)));
|
||||
|
||||
private static void AssertUniform(ImageBuffer image, double expected, double tolerance)
|
||||
{
|
||||
for (var c = 0; c < image.Channels; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
for (var i = 0; i < plane.Length; i++)
|
||||
{
|
||||
if (Math.Abs(plane[i] - expected) > tolerance)
|
||||
Assert.Fail($"channel {c} pixel {i}: expected {expected:F5} ± {tolerance}, actual {plane[i]:F5}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Codecs.Png;
|
||||
using Titano.Core.Windows.Interop;
|
||||
using Titano.Core.Windows.Wic;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
/// <summary>Synthetic fixtures: PNG through the managed encoder, JPEG through WIC's own encoder.</summary>
|
||||
internal static unsafe partial class WicTestImages
|
||||
{
|
||||
private static readonly Guid JpegContainer = new("19e4a5aa-5662-4fc5-a0c0-1758028e1057");
|
||||
private static readonly Guid PixelFormat8bppGray = new("6fddc324-4e03-4bfe-b185-3d77768dc908");
|
||||
|
||||
private const uint STGM_WRITE = 0x1, STGM_SHARE_EXCLUSIVE = 0x10, STGM_CREATE = 0x1000;
|
||||
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
|
||||
private const int WICBitmapEncoderNoCache = 2;
|
||||
|
||||
public static void WriteRgbPng(string path, int width, int height, Func<int, int, (byte R, byte G, byte B)> pixel)
|
||||
{
|
||||
var data = new byte[width * height * 3];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (r, g, b) = pixel(x, y);
|
||||
var i = ((y * width) + x) * 3;
|
||||
data[i] = r;
|
||||
data[i + 1] = g;
|
||||
data[i + 2] = b;
|
||||
}
|
||||
}
|
||||
File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Rgb));
|
||||
}
|
||||
|
||||
public static void WriteGray16Png(string path, int width, int height, ushort value)
|
||||
{
|
||||
var data = new byte[width * height * 2];
|
||||
for (var i = 0; i < data.Length; i += 2) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(i), value);
|
||||
File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Gray, bitDepth: 16));
|
||||
}
|
||||
|
||||
/// <summary>Grayscale baseline JPEG from WIC's encoder; optionally tagged with an Exif orientation.</summary>
|
||||
public static void WriteGrayJpeg(string path, int width, int height, Func<int, int, byte> gray, int? exifOrientation = null)
|
||||
{
|
||||
var pixels = new byte[width * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++) pixels[(y * width) + x] = gray(x, y);
|
||||
}
|
||||
|
||||
var container = JpegContainer;
|
||||
Marshal.ThrowExceptionForHR(WicFactory.Instance.CreateEncoder(ref container, 0, out var encoderPointer));
|
||||
IWICBitmapEncoder encoder;
|
||||
try
|
||||
{
|
||||
encoder = (IWICBitmapEncoder)Marshal.GetObjectForIUnknown(encoderPointer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.Release(encoderPointer);
|
||||
}
|
||||
|
||||
Marshal.ThrowExceptionForHR(SHCreateStreamOnFileEx(path, STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, FILE_ATTRIBUTE_NORMAL, 1, 0, out var stream));
|
||||
IWICBitmapFrameEncode? frame = null;
|
||||
nint options = 0;
|
||||
try
|
||||
{
|
||||
encoder.Initialize(stream, WICBitmapEncoderNoCache);
|
||||
encoder.CreateNewFrame(out frame, out options);
|
||||
frame.Initialize(options);
|
||||
frame.SetSize((uint)width, (uint)height);
|
||||
var format = PixelFormat8bppGray;
|
||||
frame.SetPixelFormat(ref format);
|
||||
if (format != PixelFormat8bppGray) throw new InvalidOperationException("The WIC JPEG encoder did not accept 8bppGray.");
|
||||
fixed (byte* p = pixels) frame.WritePixels((uint)height, (uint)width, (uint)pixels.Length, (nint)p);
|
||||
frame.Commit();
|
||||
encoder.Commit();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(frame);
|
||||
if (options != 0) Marshal.Release(options);
|
||||
Win32Com.Release(encoder);
|
||||
Marshal.Release(stream);
|
||||
}
|
||||
|
||||
if (exifOrientation is { } orientation) InsertExifOrientation(path, orientation);
|
||||
}
|
||||
|
||||
/// <summary>Adds an APP1 Exif segment holding only IFD0 Orientation (after APP0 when present, as cameras do).</summary>
|
||||
private static void InsertExifOrientation(string path, int orientation)
|
||||
{
|
||||
var jpeg = File.ReadAllBytes(path);
|
||||
byte[] tiff =
|
||||
[
|
||||
(byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0, // little-endian header, IFD0 at offset 8
|
||||
1, 0, // one entry
|
||||
0x12, 0x01, 3, 0, 1, 0, 0, 0, (byte)orientation, 0, 0, 0, // 0x0112 Orientation, SHORT, count 1
|
||||
0, 0, 0, 0, // no next IFD
|
||||
];
|
||||
var insertAt = 2;
|
||||
if (jpeg[2] == 0xFF && jpeg[3] == 0xE0) insertAt = 4 + BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(4));
|
||||
var segmentLength = 2 + 6 + tiff.Length;
|
||||
using var output = new MemoryStream();
|
||||
output.Write(jpeg, 0, insertAt);
|
||||
output.Write([0xFF, 0xE1, (byte)(segmentLength >> 8), (byte)segmentLength]);
|
||||
output.Write("Exif\0\0"u8);
|
||||
output.Write(tiff);
|
||||
output.Write(jpeg, insertAt, jpeg.Length - insertAt);
|
||||
File.WriteAllBytes(path, output.ToArray());
|
||||
}
|
||||
|
||||
[LibraryImport("shlwapi.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000103-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapEncoder
|
||||
{
|
||||
void Initialize(nint stream, int cacheOption);
|
||||
|
||||
Guid GetContainerFormat();
|
||||
|
||||
void GetEncoderInfo(out nint encoderInfo);
|
||||
|
||||
void SetColorContexts(uint count, nint colorContexts);
|
||||
|
||||
void SetPalette(nint palette);
|
||||
|
||||
void SetThumbnail(nint thumbnail);
|
||||
|
||||
void SetPreview(nint preview);
|
||||
|
||||
void CreateNewFrame(out IWICBitmapFrameEncode frame, out nint encoderOptions);
|
||||
|
||||
void Commit();
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000105-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapFrameEncode
|
||||
{
|
||||
void Initialize(nint encoderOptions);
|
||||
|
||||
void SetSize(uint width, uint height);
|
||||
|
||||
void SetResolution(double dpiX, double dpiY);
|
||||
|
||||
void SetPixelFormat(ref Guid pixelFormat);
|
||||
|
||||
void SetColorContexts(uint count, nint colorContexts);
|
||||
|
||||
void SetPalette(nint palette);
|
||||
|
||||
void SetThumbnail(nint thumbnail);
|
||||
|
||||
void WritePixels(uint lineCount, uint stride, uint bufferSize, nint pixels);
|
||||
|
||||
void WriteSource(nint source, nint rect);
|
||||
|
||||
void Commit();
|
||||
}
|
||||
Reference in new issue
Block a user