Skip to content

Commit

Permalink
Added: Forced Image Resize to JXL Converter
Browse files Browse the repository at this point in the history
  • Loading branch information
Sewer56 committed Oct 16, 2022
1 parent 3ed9613 commit 948c954
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions source/Reloaded.Mod.Launcher.Lib/Utility/JxlImageConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
namespace Reloaded.Mod.Launcher.Lib.Utility;

/// <summary>
/// Converts images to JPEG XL format.
/// Converts images to JPEG XL format, with maximum 1080p resolution.
/// </summary>
public class JxlImageConverter : IModPackImageConverter
{
private const int MaxWidth = 1920;
private const int MaxHeight = 1080;

/// <summary>
/// Static instance of the class.
/// </summary>
Expand All @@ -21,15 +24,35 @@ static JxlImageConverter()
}

/// <inheritdoc />
public MemoryStream Convert(Span<byte> source, string extension, out string newExtension)
public unsafe MemoryStream Convert(Span<byte> source, string extension, out string newExtension)
{
var settings = new ProcessImageSettings();
settings.TrySetEncoderFormat(ImageMimeTypes.Jxl);
settings.EncoderOptions = EncoderOptions;

var output = new MemoryStream();
MagicImageProcessor.ProcessImage(source, output, settings);

fixed (byte* firstByte = &source[0])
{
// TODO: This is a bit inefficient as some additional work is done to build the initial pipeline, but I can't find an API in ImageScaler just to decode and some sources (\*cough\*) GameBanana force converted to WebP which wouldn't be supported by System.Drawing.Common.
var sourceStream = new UnmanagedMemoryStream(firstByte, source.Length);
using var pipeline = MagicImageProcessor.BuildPipeline(sourceStream, settings);

// Scale image to max width/height.
var ratioX = (double)MaxWidth / pipeline.PixelSource.Width;
var ratioY = (double)MaxHeight / pipeline.PixelSource.Height;
var ratio = Math.Min(ratioX, ratioY);

// Only scale down
if (ratio < 1)
{
settings.Width = (int)(pipeline.PixelSource.Width * ratio);
settings.Height = (int)(pipeline.PixelSource.Height * ratio);
}

sourceStream.Position = 0;
MagicImageProcessor.ProcessImage(sourceStream, output, settings);
}

output.Position = 0;
newExtension = ".jxl";
return output;
Expand Down

0 comments on commit 948c954

Please sign in to comment.