0
0

Add thumbnail file creation

This commit is contained in:
Sergey Chebotar 2023-06-05 07:01:44 +03:00
parent e5416aff88
commit 14312cb5c6
5 changed files with 174 additions and 109 deletions

View File

@ -3,131 +3,141 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MyDarling.Models; using MyDarling.Models;
using MyDarling.Services;
namespace MyDarling.Controllers namespace MyDarling.Controllers
{ {
[Authorize] [Authorize]
public class ProductsController : Controller public class ProductsController : Controller
{ {
private DataContext context; private DataContext context;
private IWebHostEnvironment environment; private IWebHostEnvironment environment;
private IImageResizer resizer;
public ProductsController(DataContext context, IWebHostEnvironment environment) public ProductsController(DataContext context, IImageResizer resizer, IWebHostEnvironment environment)
{ {
this.environment = environment; this.environment = environment;
this.context = context; this.context = context;
} this.resizer = resizer;
}
public IActionResult Index() public IActionResult Index()
{ {
return View(context.Products.Include(b => b.Figures)); return View(context.Products.Include(b => b.Figures));
} }
public IActionResult Create() public IActionResult Create()
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> Create([Bind] Product bundle) public async Task<IActionResult> Create([Bind] Product bundle)
{ {
try try
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
await context.Products.AddAsync(bundle); await context.Products.AddAsync(bundle);
context.SaveChanges(); context.SaveChanges();
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }
} }
catch (DataException) catch (DataException)
{ {
ModelState.AddModelError("", "Unable to save changes"); ModelState.AddModelError("", "Unable to save changes");
} }
return View(bundle); return View(bundle);
} }
public async Task<IActionResult> Details(string id) public async Task<IActionResult> Details(string id)
{ {
return View(await context.Products.Include(b => b.Figures).Where(b => b.Id.Equals(id)).FirstOrDefaultAsync()); return View(await context.Products.Include(b => b.Figures).Where(b => b.Id.Equals(id)).FirstOrDefaultAsync());
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> Edit(string id) public async Task<IActionResult> Edit(string id)
{ {
if (string.IsNullOrEmpty(id)) if (string.IsNullOrEmpty(id))
{ {
return NotFound(); return NotFound();
} }
var product = await context.Products.FindAsync(id); var product = await context.Products.FindAsync(id);
if (product == null) if (product == null)
{ {
return NotFound(); return NotFound();
} }
var file = Request.Form.Files.FirstOrDefault(); var file = Request.Form.Files.FirstOrDefault();
string fullPath = string.Empty;
if (await TryUpdateModelAsync<Product>( if (await TryUpdateModelAsync<Product>(
product, product,
"", "",
b => b.Name, b => b.Description, b => b.Figures, b => b.Price)) b => b.Name, b => b.Description, b => b.Figures, b => b.Price))
{ {
if (file != null) if (file != null)
{ {
var newFigure = new Figure(string.Empty, product.Id); var newFigure = new Figure(string.Empty, product.Id);
product.Figures.Add(newFigure); product.Figures.Add(newFigure);
string filePath = $"/Content/{product.Id}/{newFigure.Id}.jpg"; string filePath = $"/Content/{product.Id}/{newFigure.Id}.jpg";
var savePath = environment.WebRootPath + "/Content/" + product.Id + "/"; string directoryPath = environment.WebRootPath + "/Content/" + product.Id + "/";
if (!Directory.Exists(savePath)) fullPath = environment.WebRootPath + filePath;
{ if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(savePath); {
} Directory.CreateDirectory(directoryPath);
using var fileStream = new FileStream(environment.WebRootPath + filePath, FileMode.Create); }
await file.CopyToAsync(fileStream); using var fileStream = new FileStream(fullPath, FileMode.Create);
} await file.CopyToAsync(fileStream);
}
try if (!string.IsNullOrEmpty(fullPath))
{ {
await context.SaveChangesAsync(); resizer.CreateThumbnail(fullPath);
}
try
{
await context.SaveChangesAsync();
return RedirectToAction("Details", "Products", new { Id = product?.Id}); return RedirectToAction("Details", "Products", new { Id = product?.Id});
} }
catch (System.Exception) catch (System.Exception)
{ {
ModelState.AddModelError("", "Unable to save changes"); ModelState.AddModelError("", "Unable to save changes");
} }
} }
return View(product); return View(product);
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> Delete(string id) public async Task<IActionResult> Delete(string id)
{ {
var productToDelete = await context.Products.FindAsync(id); var productToDelete = await context.Products.FindAsync(id);
if (productToDelete == null) if (productToDelete == null)
{ {
return NotFound(); return NotFound();
} }
try try
{ {
var bundleDirPath = String.Concat(environment.WebRootPath, var bundleDirPath = String.Concat(environment.WebRootPath,
"/Content/", "/Content/",
productToDelete.Id); productToDelete.Id);
if (Directory.Exists(bundleDirPath)) if (Directory.Exists(bundleDirPath))
{ {
Directory.Delete(bundleDirPath, true); Directory.Delete(bundleDirPath, true);
} }
context.Products.Remove(productToDelete); context.Products.Remove(productToDelete);
await context.SaveChangesAsync(); await context.SaveChangesAsync();
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true }); return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true });
} }
} }
} }
} }

View File

@ -13,6 +13,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="SkiaSharp" Version="2.88.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,7 +1,9 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MyDarling.Models; using MyDarling.Models;
using MyDarling.Services;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DataContext>(opts => builder.Services.AddDbContext<DataContext>(opts =>
@ -25,6 +27,7 @@ builder.Services.Configure<IdentityOptions>( opts =>
opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz"; opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
}); });
builder.Services.AddTransient<IImageResizer, ImageResizer>();
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();

View File

@ -0,0 +1,8 @@
namespace MyDarling.Services
{
public interface IImageResizer
{
public void CreateThumbnail(string filePath);
public void DownsizeImage(string filePath);
}
}

43
Services/ImageResizer.cs Normal file
View File

@ -0,0 +1,43 @@
using SkiaSharp;
namespace MyDarling.Services
{
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);
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);
var outputPath = Path.GetDirectoryName(inputPath) + "\\" +
Path.GetFileNameWithoutExtension(inputPath) + "_thumb.jpg";
using var output = File.OpenWrite(outputPath);
image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(output);
}
public void DownsizeImage(string filePath)
{
throw new NotImplementedException();
}
}
}