How to optimize the size of images with Tinify?
Here we will use a 3rd party library Tinify API. This API offers 500 compression options per month for free. I foresee that this figure will be sufficient for bloggers like me. But I will not leave myself dependent on this situation. Do not neglect to code to bypass the Api anyway.
Tinify processes the file you upload to the system and performs size reduction up to 70% without compromising the quality of the picture. From time to time I witnessed that the 5mb size image dropped to 270kb. I think it is useful to consider the performance this will give to your application.
To use the library, get the Key from the link above. Let's start coding after getting the key.
First, let's install the library. Nuget
Install-Package Tinify
Şimdi Startup.cs girip ConfigureServices içerisinde projemize API'den aldığımız keyi girelim.
Tinify.Key = "ApiKey";
Now let's enter Startup.cs and enter the key we got from our project API in ConfigureServices.
public class FilesController : Controller
{
public static IWebHostEnvironment _webHostEnvironment;
public FilesController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
[HttpPost]
public async Task<JsonResult> FileUpload(IFormFile file, string entityType, int entiyId)
{
try
{
if (!(file?.Length > 0))
return new JsonResult("NotFound");
var model = await UploadLocalFileSystem(file, entityType, entiyId);
return new JsonResult(new {Data = model});
}
catch (Exception ex)
{
return new JsonResult(new {Error = new {Code = 500, Message = ex.Message, Type = "Exception"}});
}
}
}
Let's process our file after the request is received in the controller. (string entityType, int entiyId) You can delete this parameter and its associated locations. I have added these parameters to control which picture is attached for what and where. Also, when using Path and Directory, you may encounter situations that require you to prepend System.IO. If you have problems with this topic, we'll meet in the comments.
public async Task<Files> UploadLocalFileSystem(IFormFile file, string entityType, int entiyId)
{
var files = Path.Combine(_webHostEnvironment.WebRootPath, "files");
var originals = Path.Combine(_webHostEnvironment.WebRootPath, "originals");
var existsfiles = Directory.Exists(files);
var existsoriginals = Directory.Exists(originals);
if (!existsfiles) Directory.CreateDirectory(files);
if (!existsoriginals) Directory.CreateDirectory(originals);
var extension = Path.GetExtension(file.FileName);
var model = new Files // Your database model. Here we log our files added to the system to the database.
{
EntityName = entityType,
EntityId = entiyId,
Extension = extension,
ContentType = file.ContentType,
Size = file.Length
};
if (file.ContentType.Contains("image"))
{
await using var fileStream = new FileStream(Path.Combine(originals, model.Guid + extension), FileMode.Create);
await file.CopyToAsync(fileStream);
await using var ms = new MemoryStream();
await file.CopyToAsync(ms);
var fileBytes = ms.ToArray();
var resultData = await Tinify.FromBuffer(fileBytes).ToBuffer();
await File.WriteAllBytesAsync(Path.Combine(files, model.Guid + extension), resultData);
}
else
{
await using var fileStream = new FileStream(Path.Combine(files, model.Guid + extension), FileMode.Create);
await file.CopyToAsync(fileStream);
}
return Insert(model); // Your database model. We send it to the service to add it to the database.
}
Hadi selametle!