Код: Выделить всё
public async static Task SaveAsync(this IFormFile file, string path, string folder)
{
string baseUrl = "";
var filePath = Path.Combine(path, folder);
bool exists = Directory.Exists(filePath);
if (!exists)
Directory.CreateDirectory(filePath);
var fileName = Path.Combine(Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
string resultPath = Path.Combine(filePath, fileName);
if (file.IsImage())
{
if (file.ContentType.Contains("jpeg") || file.ContentType.Contains("jpg"))
{
using (var image = SixLabors.ImageSharp.Image.Load(file.OpenReadStream()))
{
var encoder = new JpegEncoder { Quality = 75 }; // Adjust quality as needed
await image.SaveAsync(resultPath, encoder);
}
}
// Part where .gif compression happens
else if (file.ContentType.Contains("gif"))
{
using (var gifStream = new MemoryStream())
{
await file.CopyToAsync(gifStream);
gifStream.Seek(0, System.IO.SeekOrigin.Begin);
using (var imageCollection = new MagickImageCollection(gifStream))
{
imageCollection.Coalesce();
int maxWidth = 0;
int maxHeight = 0;
foreach (var frame in imageCollection)
{
if (frame.Width > maxWidth)
maxWidth = frame.Width;
if (frame.Height > maxHeight)
maxHeight = frame.Height;
}
foreach (var frame in imageCollection)
{
frame.BackgroundColor = MagickColors.Transparent;
frame.Extent(maxWidth, maxHeight, Gravity.Center);
}
imageCollection.Optimize();
var settings = new QuantizeSettings
{
Colors = 128
};
imageCollection.Quantize(settings);
imageCollection.OptimizeTransparency();
foreach (var frame in imageCollection)
{
frame.Interlace = Interlace.Plane;
frame.Depth = 8;
}
await imageCollection.WriteAsync(resultPath);
}
}
}
else
{
using (var fileStream = new FileStream(resultPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
else
{
using (var fileStream = new FileStream(resultPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return $"{baseUrl}{folder}/{fileName}";
}
public static bool IsImage(this IFormFile file)
{
return file.ContentType.Contains("image/");
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... erformance