benscode-StitcherApi/Services/ImageService.cs

64 lines
2.1 KiB
C#
Raw Permalink Normal View History

2025-07-31 19:39:06 +07:00
using StitcherApi.Models;
using StitcherApi.Services.Utilities;
namespace StitcherApi.Services;
public class ImageService : IImageService
{
private readonly ImageProcessor _processor;
private const int TILE_SIZE = 720;
public ImageService(IConfiguration configuration)
{
string assetPath =
configuration["AssetPath"]
?? throw new InvalidOperationException("AssetPath is not configured.");
_processor = new ImageProcessor(assetPath);
}
public async Task<byte[]> GenerateImageAsync(GenerateImageRequest request)
{
// 1. Delegate parsing to the CoordinateParser
(int minRow, int minCol, int maxRow, int maxCol) = CoordinateParser.ParseCanvasRect(
request.CanvasRect
);
2025-07-31 19:39:06 +07:00
// 2. Perform high-level calculations
int stitchedCanvasWidth = (maxCol - minCol + 1) * TILE_SIZE;
int stitchedCanvasHeight = (maxRow - minRow + 1) * TILE_SIZE;
2025-07-31 19:39:06 +07:00
int cropX = (int)(request.CropOffset[0] * stitchedCanvasWidth);
int cropY = (int)(request.CropOffset[1] * stitchedCanvasHeight);
int cropW = (int)(request.CropSize[0] * stitchedCanvasWidth);
int cropH = (int)(request.CropSize[1] * stitchedCanvasHeight);
if (cropW <= 0 || cropH <= 0)
{
throw new ArgumentException("Calculated crop dimensions are invalid.");
}
int startTileCol = minCol + (cropX / TILE_SIZE);
int endTileCol = minCol + ((cropX + cropW - 1) / TILE_SIZE);
int startTileRow = minRow + (cropY / TILE_SIZE);
int endTileRow = minRow + ((cropY + cropH - 1) / TILE_SIZE);
2025-07-31 19:39:06 +07:00
// 3. Create a parameter object for the processor
StitchRequest stitchRequest = new StitchRequest(
2025-07-31 19:39:06 +07:00
minRow,
minCol,
startTileRow,
startTileCol,
endTileRow,
endTileCol,
cropX,
cropY,
cropW,
cropH,
request.OutputScale
);
// 4. Delegate image processing work
return await _processor.StitchAndCropAsync(stitchRequest);
}
}