60 lines
No EOL
2.1 KiB
C#
60 lines
No EOL
2.1 KiB
C#
using System.Text.Json;
|
|
using StitchATon2.App.Models;
|
|
using StitchATon2.Domain;
|
|
|
|
namespace StitchATon2.App.Controllers;
|
|
|
|
public static class ImageController
|
|
{
|
|
public static async Task GenerateImage(
|
|
HttpResponse response,
|
|
GenerateImageDto dto,
|
|
TileManager tileManager,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (dto.GetErrors() is { Count: > 0 } errors)
|
|
{
|
|
response.StatusCode = 422;
|
|
response.ContentType = "text/json";
|
|
var errorBody = JsonSerializer.Serialize(errors, AppJsonSerializerContext.Default.DictionaryStringListString);
|
|
response.ContentLength = errorBody.Length;
|
|
await response.WriteAsync(errorBody, cancellationToken: cancellationToken);
|
|
await response.CompleteAsync();
|
|
return;
|
|
}
|
|
|
|
response.StatusCode = 200;
|
|
response.ContentType = "image/png";
|
|
|
|
await tileManager
|
|
.CreateSection(dto)
|
|
.DangerousWriteToPipe(response.BodyWriter, dto.OutputScale, cancellationToken);
|
|
|
|
await response.CompleteAsync();
|
|
}
|
|
|
|
public static async Task GenerateRandomImage(
|
|
HttpResponse response,
|
|
TileManager tileManager,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
response.StatusCode = 200;
|
|
response.ContentType = "image/png";
|
|
|
|
var maxId = tileManager.Configuration.Rows * tileManager.Configuration.Columns;
|
|
var id0 = Random.Shared.Next(maxId);
|
|
var id1 = Random.Shared.Next(maxId);
|
|
|
|
var tile0 = tileManager.GetTile(id0);
|
|
var tile1 = tileManager.GetTile(id1);
|
|
var coordinatePair = $"{tile0.Coordinate}:{tile1.Coordinate}";
|
|
|
|
var section = tileManager.CreateSection(coordinatePair, 0, 0, 1, 1);
|
|
|
|
var scale = float.Clamp(480f / int.Max(section.Width, section.Height), 0.01f, 1f);
|
|
Console.WriteLine($"Generate random image for {coordinatePair} scale: {scale}");
|
|
|
|
await section.DangerousWriteToPipe(response.BodyWriter, scale, cancellationToken);
|
|
await response.CompleteAsync();
|
|
}
|
|
} |