51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using SixLabors.ImageSharp;
|
|
using SixLabors.ImageSharp.Formats.Webp;
|
|
|
|
namespace Convert_It_Online.Areas.ImageConverters.Controllers
|
|
{
|
|
[Area("ImageConverters")]
|
|
public class JpgToWebpController : Controller
|
|
{
|
|
public IActionResult Index()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<IActionResult> Convert(IFormFile jpgFile)
|
|
{
|
|
if (jpgFile == null || jpgFile.Length == 0)
|
|
{
|
|
ModelState.AddModelError("jpgFile", "Por favor, selecione um arquivo.");
|
|
return View("Index");
|
|
}
|
|
|
|
// Validação simples do tipo de arquivo
|
|
if (jpgFile.ContentType != "image/jpeg")
|
|
{
|
|
ModelState.AddModelError("jpgFile", "Arquivo inválido. Por favor, envie um arquivo JPG.");
|
|
return View("Index");
|
|
}
|
|
|
|
try
|
|
{
|
|
using var imageStream = jpgFile.OpenReadStream();
|
|
using var image = await Image.LoadAsync(imageStream);
|
|
|
|
using var memoryStream = new MemoryStream();
|
|
await image.SaveAsync(memoryStream, new WebpEncoder());
|
|
memoryStream.Position = 0;
|
|
|
|
var fileName = Path.GetFileNameWithoutExtension(jpgFile.FileName) + ".webp";
|
|
return File(memoryStream.ToArray(), "image/webp", fileName);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Log do erro (não implementado aqui)
|
|
ModelState.AddModelError("jpgFile", "Ocorreu um erro ao processar a imagem.");
|
|
return View("Index");
|
|
}
|
|
}
|
|
}
|
|
} |