2023-06-05 07:01:44 +03:00
|
|
|
using SkiaSharp;
|
|
|
|
|
|
|
|
namespace MyDarling.Services
|
|
|
|
{
|
2023-06-05 17:11:36 +03:00
|
|
|
public class ImageResizer : IImageResizer
|
2023-06-05 07:01:44 +03:00
|
|
|
{
|
|
|
|
public void CreateThumbnail(string inputPath)
|
|
|
|
{
|
|
|
|
using var input = File.OpenRead(inputPath);
|
|
|
|
using var inputStream = new SKManagedStream(input);
|
2023-06-05 17:11:36 +03:00
|
|
|
var outputPath = Path.GetDirectoryName(inputPath) + "\\" +
|
|
|
|
Path.GetFileNameWithoutExtension(inputPath) + "_thumb.jpg";
|
|
|
|
WriteResized(inputStream, 600, outputPath);
|
|
|
|
}
|
|
|
|
public void WriteResized(IFormFile formFile, string outputFilePath)
|
|
|
|
{
|
|
|
|
SKManagedStream stream = new(formFile.OpenReadStream());
|
|
|
|
WriteResized(stream, 2000, outputFilePath);
|
|
|
|
}
|
|
|
|
|
|
|
|
private void WriteResized(SKManagedStream stream, int size, string outputFilePath)
|
|
|
|
{
|
|
|
|
int quality = 95;
|
|
|
|
var skData = SKData.Create(stream);
|
|
|
|
using var original = SKBitmap.Decode(skData);
|
2023-06-05 07:01:44 +03:00
|
|
|
|
|
|
|
int width, height;
|
|
|
|
if (original.Width > original.Height)
|
|
|
|
{
|
|
|
|
width = size;
|
|
|
|
height = original.Height * size / original.Width;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
width = original.Width * size / original.Height;
|
|
|
|
height = size;
|
|
|
|
}
|
|
|
|
|
|
|
|
using var resized = original.Resize(new SKImageInfo(width, height), SKFilterQuality.High);
|
|
|
|
if (resized == null) return;
|
|
|
|
|
|
|
|
using var image = SKImage.FromBitmap(resized);
|
2023-06-05 17:11:36 +03:00
|
|
|
using var output = File.OpenWrite(outputFilePath);
|
2023-06-05 07:01:44 +03:00
|
|
|
|
|
|
|
image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(output);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|