70 lines
2.1 KiB
C#
70 lines
2.1 KiB
C#
using DomainResults.Common;
|
|
using ImageProvider.Fonts;
|
|
using Microsoft.Extensions.Logging;
|
|
using SixLabors.Fonts;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ImageProvider {
|
|
|
|
public interface IImageProvider {
|
|
(byte[]?, IDomainResult) Resize(byte[] bytes, int width, int height);
|
|
(byte[]?, IDomainResult) ResizeAndWatermark(byte[] bytes, int width, int height, FontsEnum fontName, FontStylesEnum fontStyle, string text);
|
|
}
|
|
|
|
public class ImageProvider : IImageProvider {
|
|
|
|
private readonly ILogger<ImageProvider> _logger;
|
|
private readonly IFontCollection _fontCollection;
|
|
|
|
public ImageProvider(
|
|
ILogger<ImageProvider> logger,
|
|
IFontCollection fontCollection
|
|
) {
|
|
_logger = logger;
|
|
_fontCollection = fontCollection;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="bytes"></param>
|
|
/// <param name="width"></param>
|
|
/// <param name="height"></param>
|
|
/// <returns></returns>
|
|
public (byte[]?, IDomainResult) Resize(byte[] bytes, int width, int height) {
|
|
try {
|
|
using var imageBuilder = new ImageBuilder(bytes);
|
|
imageBuilder.Resize(width, height);
|
|
|
|
return IDomainResult.Success(imageBuilder.ToJpeg());
|
|
}
|
|
catch (Exception ex) {
|
|
_logger.LogError("Unhandled exception", ex);
|
|
return IDomainResult.Failed<byte[]?>();
|
|
}
|
|
}
|
|
|
|
public (byte[]?, IDomainResult) ResizeAndWatermark(byte[] bytes, int width, int height, FontsEnum fontName, FontStylesEnum fontStyle, string text) {
|
|
try {
|
|
var font = _fontCollection.Families.Single(x => x.Name == fontName.Name)
|
|
.CreateFont(10, fontStyle.FontStyle);
|
|
|
|
using var imageBuilder = new ImageBuilder(bytes);
|
|
imageBuilder.FitWidthResize(width);
|
|
imageBuilder.Crop(width, height);
|
|
// imageBuilder.Watermark(font, text);
|
|
|
|
return IDomainResult.Success(imageBuilder.ToJpeg());
|
|
}
|
|
catch (Exception ex) {
|
|
_logger.LogError("Unhandled exception", ex);
|
|
return IDomainResult.Failed<byte[]?>();
|
|
}
|
|
}
|
|
}
|
|
}
|