0
0

Resize image on Upload

This commit is contained in:
Sergey Chebotar 2023-06-05 17:11:36 +03:00
parent 0f5cbb4d87
commit 480faae00b
3 changed files with 20 additions and 15 deletions

View File

@ -88,8 +88,8 @@ namespace MyDarling.Controllers
{ {
Directory.CreateDirectory(directoryPath); Directory.CreateDirectory(directoryPath);
} }
using var fileStream = new FileStream(fullPath, FileMode.Create);
await file.CopyToAsync(fileStream); resizer.WriteResized(file, fullPath);
} }
if (!string.IsNullOrEmpty(fullPath)) if (!string.IsNullOrEmpty(fullPath))

View File

@ -2,7 +2,7 @@ namespace MyDarling.Services
{ {
public interface IImageResizer public interface IImageResizer
{ {
public void WriteResized(IFormFile formFile, string outputFilePath);
public void CreateThumbnail(string filePath); public void CreateThumbnail(string filePath);
public void DownsizeImage(string filePath);
} }
} }

View File

@ -2,15 +2,27 @@ using SkiaSharp;
namespace MyDarling.Services namespace MyDarling.Services
{ {
public class ImageResizer : IImageResizer public class ImageResizer : IImageResizer
{ {
const int size = 400;
const int quality = 75;
public void CreateThumbnail(string inputPath) public void CreateThumbnail(string inputPath)
{ {
using var input = File.OpenRead(inputPath); using var input = File.OpenRead(inputPath);
using var inputStream = new SKManagedStream(input); using var inputStream = new SKManagedStream(input);
using var original = SKBitmap.Decode(inputStream); 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);
int width, height; int width, height;
if (original.Width > original.Height) if (original.Width > original.Height)
@ -28,16 +40,9 @@ namespace MyDarling.Services
if (resized == null) return; if (resized == null) return;
using var image = SKImage.FromBitmap(resized); using var image = SKImage.FromBitmap(resized);
var outputPath = Path.GetDirectoryName(inputPath) + "\\" + using var output = File.OpenWrite(outputFilePath);
Path.GetFileNameWithoutExtension(inputPath) + "_thumb.jpg";
using var output = File.OpenWrite(outputPath);
image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(output); image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(output);
} }
public void DownsizeImage(string filePath)
{
throw new NotImplementedException();
}
} }
} }