Resize image on Upload
This commit is contained in:
parent
0f5cbb4d87
commit
480faae00b
@ -88,8 +88,8 @@ namespace MyDarling.Controllers
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
using var fileStream = new FileStream(fullPath, FileMode.Create);
|
||||
await file.CopyToAsync(fileStream);
|
||||
|
||||
resizer.WriteResized(file, fullPath);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(fullPath))
|
||||
|
@ -2,7 +2,7 @@ namespace MyDarling.Services
|
||||
{
|
||||
public interface IImageResizer
|
||||
{
|
||||
public void WriteResized(IFormFile formFile, string outputFilePath);
|
||||
public void CreateThumbnail(string filePath);
|
||||
public void DownsizeImage(string filePath);
|
||||
}
|
||||
}
|
@ -2,15 +2,27 @@ using SkiaSharp;
|
||||
|
||||
namespace MyDarling.Services
|
||||
{
|
||||
public class ImageResizer : IImageResizer
|
||||
public class ImageResizer : IImageResizer
|
||||
{
|
||||
const int size = 400;
|
||||
const int quality = 75;
|
||||
public void CreateThumbnail(string inputPath)
|
||||
{
|
||||
using var input = File.OpenRead(inputPath);
|
||||
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;
|
||||
if (original.Width > original.Height)
|
||||
@ -28,16 +40,9 @@ namespace MyDarling.Services
|
||||
if (resized == null) return;
|
||||
|
||||
using var image = SKImage.FromBitmap(resized);
|
||||
var outputPath = Path.GetDirectoryName(inputPath) + "\\" +
|
||||
Path.GetFileNameWithoutExtension(inputPath) + "_thumb.jpg";
|
||||
using var output = File.OpenWrite(outputPath);
|
||||
using var output = File.OpenWrite(outputFilePath);
|
||||
|
||||
image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(output);
|
||||
}
|
||||
|
||||
public void DownsizeImage(string filePath)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user