I want to reduce file size and store it in the root folder ex. if I upload a user image from IFromFile then there should be two files stored first the original one and the other one compressed I have tried GZip but it is producing zero byte file size
Loading

Marvin ReidRank #1,963 · 746 reputationPosted Oct 9, 2023, 2:07 PM EDT
You can use the RasterCodecs class to apply Jpeg compression which is a common way to reduce file size. One can manipulate the Q Factor to determine the degree of loss applied from the compression. For a higher compression ratio, you can set the QualityFactor to a bigger number. For less compression you can keep it at 2. Here is an example:
using (RasterCodecs codecs = new RasterCodecs()) { RasterImage image = codecs.Load(@"input file path"); codecs.Options.Jpeg.Save.QualityFactor = 2; // Where 2 is the highest quality image codecs.Save(image, @"output file path ", RasterImageFormat.Jpeg, 0); }https://www.leadtools.com/help/sdk/main/api/file-formats-jpeg-and-lead-compressed-jpg-j2k-jp2-jpm-jls-cmp-and-cmw.html
https://www.leadtools.com/help/sdk/v22/dh/co/codecsjpegsaveoptions-qualityfactor.html
Amit MohantyRank #112 · 20K reputationPosted Sep 27, 2023, 6:32 AM EDT
You can use a ImageSharp library to reduce file size. Check the below example.
First, make sure you have ImageSharp installed.
Then you can create a method to compress and save the uploaded image.
using SixLabors.ImageSharp.Formats.Jpeg; namespace YourNamespace { public class ImageService { public async Task CompressAndSaveImageAsync(IFormFile imageFile, string outputPath, int quality = 75) { using var imageStream = imageFile.OpenReadStream(); using var image = Image.Load(imageStream); var encoder = new JpegEncoder { Quality = quality, // Adjust this value for desired compression quality }; await Task.Run(() => image.Save(outputPath, encoder)); } } }Now in your code call the CompressAndSaveImageAsync method to process and save the compressed image:
public async Task UploadImage(IFormFile imageFile) { if (imageFile == null || imageFile.Length == 0) { return BadRequest("No file uploaded"); } // Save the file as compressed var outputPath = ; var imageService = new ImageService(); await imageService.CompressAndSaveImageAsync(imageFile, outputPath, 30); // Save the original file var originalFilePath = ; using (var fileStream = new FileStream(originalFilePath, FileMode.Create)) { await imageFile.CopyToAsync(fileStream); } return Ok("Image uploaded and compressed."); }