#229 Resize cover-images on request before transfer

This commit is contained in:
Glax 2025-03-07 14:29:25 +01:00
parent c679d7c677
commit 6c5bc3685e
3 changed files with 40 additions and 3 deletions

View File

@ -1,8 +1,11 @@
using API.Schema;
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Transforms;
using static Microsoft.AspNetCore.Http.StatusCodes;
namespace API.Controllers;
@ -88,14 +91,18 @@ public class MangaController(PgsqlContext context) : Controller
/// Returns Cover of Manga
/// </summary>
/// <param name="id">Manga-ID</param>
/// <param name="formatRequest">Formatting/Resizing Request</param>
/// <response code="200">JPEG Image</response>
/// <response code="204">Cover not loaded</response>
/// <response code="400">The formatting-request was invalid</response>
/// <response code="404">Manga with ID not found</response>
[HttpGet("{id}/Cover")]
[HttpPost("{id}/Cover")]
[Produces("image/jpeg")]
[ProducesResponseType(Status200OK)]
[ProducesResponseType(Status204NoContent)]
[ProducesResponseType(Status400BadRequest)]
[ProducesResponseType(Status404NotFound)]
public IActionResult GetCover(string id)
public IActionResult GetCover(string id, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)]CoverFormatRequestRecord? formatRequest)
{
Manga? m = context.Manga.Find(id);
if (m is null)
@ -104,6 +111,18 @@ public class MangaController(PgsqlContext context) : Controller
return NoContent();
Image image = Image.Load(m.CoverFileNameInCache);
if (formatRequest is not null)
{
if(!formatRequest.Validate())
return BadRequest();
image.Mutate(i => i.ApplyProcessor(new ResizeProcessor(new ResizeOptions()
{
Mode = ResizeMode.Max,
Size = formatRequest.size
}, image.Size)));
}
using MemoryStream ms = new();
image.Save(ms, new JpegEncoder(){Quality = 100});
return File(ms.GetBuffer(), "image/jpeg");

View File

@ -0,0 +1,14 @@
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
namespace API;
public record CoverFormatRequestRecord(Size size)
{
public bool Validate()
{
if (size.Height <= 0 || size.Width <= 0 || size.Height > 65535 || size.Width > 65535) //JPEG max size
return false;
return true;
}
}

View File

@ -57,7 +57,11 @@ builder.Services.AddDbContext<PgsqlContext>(options =>
$"Username={Environment.GetEnvironmentVariable("POSTGRES_USER")??"postgres"}; " +
$"Password={Environment.GetEnvironmentVariable("POSTGRES_PASSWORD")??"postgres"}"));
builder.Services.AddControllers().AddNewtonsoftJson(opts =>
builder.Services.AddControllers(options =>
{
options.AllowEmptyInputInBodyModelBinding = true;
})
.AddNewtonsoftJson(opts =>
{
opts.SerializerSettings.Converters.Add(new StringEnumConverter());
});