#262 code for converting images to webp

This commit is contained in:
Hamid Reza Mohammadi 2021-12-17 15:23:00 +03:30
parent 356117993a
commit a2f9a6141b
2 changed files with 30 additions and 1 deletions

View File

@ -14,6 +14,8 @@
<ItemGroup>
<PackageReference Include="DNTPersianUtils.Core" Version="5.3.2" />
<PackageReference Include="ImageProcessor" Version="2.9.1" />
<PackageReference Include="ImageProcessor.Plugins.WebP" Version="1.3.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>

View File

@ -1,9 +1,12 @@
using Microsoft.EntityFrameworkCore;
using ImageProcessor;
using ImageProcessor.Plugins.WebP.Imaging.Formats;
using Microsoft.EntityFrameworkCore;
using RMuseum.DbContext;
using RSecurityBackend.Models.Generic;
using RSecurityBackend.Services.Implementation;
using System;
using System.IO;
using System.Linq;
namespace RMuseum.Services.Implementation
{
@ -48,11 +51,35 @@ namespace RMuseum.Services.Implementation
if(File.Exists(imagePath))
{
//convert to webp
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
{
imageFactory.Load(imagePath)
.Format(new WebPFormat())
.Quality(80)
.Save(webpPath);
}
}
if(File.Exists(webpPath))
{
//update db meta data
var imageInDb = await context.PictureFiles.Where(p => p.Id == image.Id).SingleAsync();
imageInDb.ContentType = "image/webp";
imageInDb.StoredFileName = imageInDb.StoredFileName.Replace(".jpg", ".webp", StringComparison.InvariantCultureIgnoreCase);
context.PictureFiles.Update(imageInDb);
await context.SaveChangesAsync();
if(File.Exists(imagePath))
{
try
{
File.Delete(imagePath);
}
catch
{
//ignore exception
}
}
}
}
}