Added extensions to save textures to files

このコミットが含まれているのは:
Sergio Pedri committed 2021-05-12 11:33:05 +02:00
1 親 c66ac3fe19
コミット f31ac94bf9
5ファイル変更
+294 -1

検索条件に一致するファイルはありません

+23
ファイルの表示
@@ -0,0 +1,23 @@
using System;
using ComputeSharp.Graphics.Helpers;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> that contains extension methods for the <see cref="ReadBackTexture2D{T}"/> type.
/// </summary>
public static class ReadBackTexture2DExtensions
{
/// <summary>
/// Saves a texture to a specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="texture">The texture to save to an image.</param>
/// <param name="filename">The filename of the image file to save.</param>
public static void Save<T>(this ReadBackTexture2D<T> texture, ReadOnlySpan<char> filename)
where T : unmanaged
{
WICHelper.Instance.SaveTexture(texture.View, filename);
}
}
}
+17
ファイルの表示
@@ -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);
}
/// <summary>
/// Saves a texture to a specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="texture">The texture to save to an image.</param>
/// <param name="filename">The filename of the image file to save.</param>
public static void Save<T>(this Texture2D<T> texture, ReadOnlySpan<char> filename)
where T : unmanaged
{
using ReadBackTexture2D<T> readback = texture.GraphicsDevice.AllocateReadBackTexture2D<T>(texture.Width, texture.Height);
texture.CopyTo(readback);
WICHelper.Instance.SaveTexture(readback.View, filename);
}
}
}
+99
ファイルの表示
@@ -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<Guid>("Invalid texture type");
}
/// <summary>
/// Gets the appropriate WIC format <see cref="Guid"/> value for the input type argument.
/// </summary>
/// <typeparam name="T">The input type argument to get the corresponding WIC format <see cref="Guid"/>.</typeparam>
/// <returns>The WIC format <see cref="Guid"/> value corresponding to <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the input type <typeparamref name="T"/> is not supported.</exception>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetIntermediateFormatForType<T>(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<Guid>("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<Guid>("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<Guid>("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<Guid>("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<Guid>("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<Guid>("Invalid texture type");
}
else
{
intermediateFormat = ThrowHelper.ThrowArgumentException<Guid>("Invalid container format");
}
return intermediateFormat != default;
}
/// <summary>
/// Gets the appropriate WIC container format <see cref="Guid"/> value for the input filename.
/// </summary>
/// <param name="filename">The target filename to get the container format for.</param>
/// <returns>The WIC format container <see cref="Guid"/> value matching <paramref name="filename"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the input filename doesn't have a valid file extension.</exception>
[Pure]
public static Guid GetForFilename(ReadOnlySpan<char> 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<Guid>("Invalid filename");
}
}
}
}
+101 -1
ファイルの表示
@@ -112,6 +112,106 @@ namespace ComputeSharp.Graphics.Helpers
}
}
/// <summary>
/// Saves a texture to a specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="texture">The texture data to save to an image.</param>
/// <param name="filename">The filename of the image file to save.</param>
public void SaveTexture<T>(TextureView2D<T> texture, ReadOnlySpan<char> filename)
where T : unmanaged
{
using ComPtr<IWICBitmapEncoder> wicBitmapEncoder = default;
Guid containerGuid = WICFormatHelper.GetForFilename(filename);
// Create the image encoder
this.wicImagingFactory2.Get()->CreateEncoder(
&containerGuid,
null,
wicBitmapEncoder.GetAddressOf()).Assert();
using ComPtr<IWICStream> 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<IWICBitmapFrameEncode> 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<T>(containerGuid, out Guid intermediateGuid))
{
T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes);
using ComPtr<IWICBitmap> wicBitmap = default;
Guid initialGuid = WICFormatHelper.GetForType<T>();
// 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<IWICFormatConverter> 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<T>();
// 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();
}
/// <summary>
/// Loads a <see cref="ReadOnlyTexture2D{T, TPixel}"/> from a specified <see cref="IWICBitmapDecoder"/> object.
/// </summary>
@@ -121,7 +221,7 @@ namespace ComputeSharp.Graphics.Helpers
/// <param name="wicBitmapDecoder">The <see cref="IWICBitmapDecoder"/> object in use.</param>
/// <returns>A <see cref="ReadOnlyTexture2D{T, TPixel}"/> instance with the contents of the specified file.</returns>
[Pure]
public ReadOnlyTexture2D<T, TPixel> LoadTexture<T, TPixel>(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder)
private ReadOnlyTexture2D<T, TPixel> LoadTexture<T, TPixel>(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
+54
ファイルの表示
@@ -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<Rgba32, Float4> texture = device.Get().AllocateReadOnlyTexture2D<Rgba32, Float4>(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<Bgra32, Float4> texture = device.Get().AllocateReadOnlyTexture2D<Bgra32, Float4>(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<R8, float> texture = device.Get().AllocateReadOnlyTexture2D<R8, float>(sourcePath);
texture.Save(actualPath);
using Image<ImageSharpL8> original = Image.Load<ImageSharpL8>(sourcePath);
original.Save(expectedPath);
TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00004037f);
}
/// <summary>
/// An tolerant image comparer type, from <see href="https://github.com/SixLabors/ImageSharp">ImageSharp</see>.
/// </summary>