From f31ac94bf964cbc89c5dc8c61e6edc419da838df Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 12 May 2021 11:17:00 +0200 Subject: [PATCH] Added extensions to save textures to files --- .../Extensions/ReadBackTexture2DExtensions.cs | 23 ++++ .../Extensions/Texture2DExtensions.cs | 17 +++ .../Graphics/Helpers/WICFormatHelper.cs | 99 +++++++++++++++++ .../Graphics/Helpers/WICHelper.cs | 102 +++++++++++++++++- tests/ComputeSharp.Tests/ImagingTests.cs | 54 ++++++++++ 5 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs diff --git a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs new file mode 100644 index 00000000..83b075cf --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs @@ -0,0 +1,23 @@ +using System; +using ComputeSharp.Graphics.Helpers; + +namespace ComputeSharp +{ + /// + /// A that contains extension methods for the type. + /// + public static class ReadBackTexture2DExtensions + { + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this ReadBackTexture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + WICHelper.Instance.SaveTexture(texture.View, filename); + } + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs index db6722f8..e1e2b755 100644 --- a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; @@ -338,5 +339,21 @@ namespace ComputeSharp { texture.CopyFrom(ref MemoryMarshal.GetReference(source), source.Length, x, y, width, height); } + + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this Texture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ReadBackTexture2D readback = texture.GraphicsDevice.AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + WICHelper.Instance.SaveTexture(readback.View, filename); + } } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs index fe65f07b..19b5716e 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using System.Runtime.CompilerServices; using Microsoft.Toolkit.Diagnostics; using FX = TerraFX.Interop.Windows; @@ -29,5 +30,103 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(R16)) return FX.GUID_WICPixelFormat16bppGray; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); } + + /// + /// Gets the appropriate WIC format value for the input type argument. + /// + /// The input type argument to get the corresponding WIC format . + /// The WIC format value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetIntermediateFormatForType(Guid containerFormat, out Guid intermediateFormat) + where T : unmanaged + { + if (containerFormat == FX.GUID_ContainerFormatBmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatPng) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatJpeg) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatWmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatTiff) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatDds) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else + { + intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid container format"); + } + + return intermediateFormat != default; + } + + /// + /// Gets the appropriate WIC container format value for the input filename. + /// + /// The target filename to get the container format for. + /// The WIC format container value matching . + /// Thrown when the input filename doesn't have a valid file extension. + [Pure] + public static Guid GetForFilename(ReadOnlySpan filename) + { + switch (Path.GetExtension(filename).ToString()) + { + case ".bmp": return FX.GUID_ContainerFormatBmp; + case ".png": return FX.GUID_ContainerFormatPng; + case ".jpg": + case ".jpeg": return FX.GUID_ContainerFormatJpeg; + case ".jxr": + case ".hdp": + case ".wdp": + case ".wmp": return FX.GUID_ContainerFormatWmp; + case ".tiff": return FX.GUID_ContainerFormatTiff; + case ".dds": return FX.GUID_ContainerFormatDds; + default: return ThrowHelper.ThrowArgumentException("Invalid filename"); + } + } } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 61cee873..83d46a75 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -112,6 +112,106 @@ namespace ComputeSharp.Graphics.Helpers } } + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture data to save to an image. + /// The filename of the image file to save. + public void SaveTexture(TextureView2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ComPtr wicBitmapEncoder = default; + Guid containerGuid = WICFormatHelper.GetForFilename(filename); + + // Create the image encoder + this.wicImagingFactory2.Get()->CreateEncoder( + &containerGuid, + null, + wicBitmapEncoder.GetAddressOf()).Assert(); + + using ComPtr wicStream = default; + + // Create and initialize a stream to the target file + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + fixed (char* p = filename) + { + wicStream.Get()->InitializeFromFilename( + (ushort*)p, + FX.GENERIC_WRITE); + } + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + (IStream*)wicStream.Get(), + WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + using ComPtr wicBitmapFrameEncode = default; + + // Create the image frame and initialize it + wicBitmapEncoder.Get()->CreateNewFrame(wicBitmapFrameEncode.GetAddressOf(), null).Assert(); + + wicBitmapFrameEncode.Get()->Initialize(null).Assert(); + wicBitmapFrameEncode.Get()->SetSize((uint)texture.Width, (uint)texture.Height).Assert(); + + // Depending on the target format and the current pixel type, we need to check whether + // an intermediate encoding step is necessary. This is because not all pixel formats + // are directly supported by the native image encoders present in Windows. + if (WICFormatHelper.TryGetIntermediateFormatForType(containerGuid, out Guid intermediateGuid)) + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + + using ComPtr wicBitmap = default; + Guid initialGuid = WICFormatHelper.GetForType(); + + // Create a bitmap wrapping the input texture + this.wicImagingFactory2.Get()->CreateBitmapFromMemory( + (uint)texture.Width, + (uint)texture.Height, + &initialGuid, + (uint)strideInBytes, + (uint)(strideInBytes * texture.Height), + (byte*)data, + wicBitmap.GetAddressOf()).Assert(); + + using ComPtr wicFormatConverter = default; + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to encode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmap.Get(), + &intermediateGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + // Write the encoded image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&intermediateGuid).Assert(); + wicBitmapFrameEncode.Get()->WriteSource( + (IWICBitmapSource*)wicBitmap.Get(), + null).Assert(); + } + else + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + Guid initialGuid = WICFormatHelper.GetForType(); + + // Write the image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&initialGuid).Assert(); + wicBitmapFrameEncode.Get()->WritePixels( + lineCount: (uint)texture.Height, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)(strideInBytes * texture.Height), + pbPixels: (byte*)data).Assert(); + } + + wicBitmapFrameEncode.Get()->Commit(); + wicBitmapEncoder.Get()->Commit(); + } + /// /// Loads a from a specified object. /// @@ -121,7 +221,7 @@ namespace ComputeSharp.Graphics.Helpers /// The object in use. /// A instance with the contents of the specified file. [Pure] - public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + private ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) where T : unmanaged, IUnorm where TPixel : unmanaged { diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 752a2cb6..6e0e7656 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -9,6 +9,7 @@ using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +using ImageSharpL8 = SixLabors.ImageSharp.PixelFormats.L8; namespace ComputeSharp.Tests { @@ -46,6 +47,59 @@ namespace ComputeSharp.Tests TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } + [CombinatorialTestMethod] + [AllDevices] + public void SaveRgba32AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); + + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveBgra32AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_bgra32_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); + + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveR8AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + sourcePath = Path.Combine(path, "city.jpg"), + expectedPath = Path.Combine(path, "city_r8_reference.jpg"), + actualPath = Path.Combine(path, "city_r8_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(sourcePath); + + texture.Save(actualPath); + + using Image original = Image.Load(sourcePath); + + original.Save(expectedPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00004037f); + } + /// /// An tolerant image comparer type, from ImageSharp. ///