2

I have developed a web-application with image upload. The users could upload all kind of images (jpg, png,...) in all kind of image sizes. Currently the image size is between 1MB and 6MB. With an API the images could be read but there is the problem. It's very slow because the size of the images is to big.

Now i would like to compress the image size to a maximum of 300KB - 500KB. I tried the library SixLabors.ImageSharp which could resize the size of an image. But the image file is still the same amount of MB big.

Could someone provide me a solution to reduze the image size?

public async Task<IActionResult> UploadImage(IFormFile file)
    {
        try
        {
            var uploads = Path.Combine(HostingEnvironment.WebRootPath, "Uploads/Images");
            var filePath = "";
            if (file.Length > 0)
            {
                filePath = Path.Combine(uploads, file.FileName);
                byte[] result = null;

                // memory stream
                using (var memoryStream = new MemoryStream())
                // filestream
                using (var image = Image.Load(file.OpenReadStream())) // IFormFile inputImage
                {
                    //var before = memoryStream.Length; Removed this, assuming you are using for debugging?
                    var beforeMutations = image.Size();

                    // dummy resize options
                    int width = 50;
                    int height = 100;
                    IResampler sampler = KnownResamplers.Lanczos3;
                    bool compand = true;
                    ResizeMode mode = ResizeMode.Stretch;

                    // init resize object
                    var resizeOptions = new ResizeOptions
                    {
                        Size = new Size(width, height),
                        Sampler = sampler,
                        Compand = compand,
                        Mode = mode
                    };

                    // mutate image
                    image.Mutate(x => x
                         .Resize(resizeOptions));

                    var afterMutations = image.Size();

                    //Encode here for quality
                    var encoder = new JpegEncoder()
                    {
                        Quality = 5 //Use variable to set between 5-30 based on your requirements
                    };

                    //This saves to the memoryStream with encoder
                    image.Save(memoryStream, encoder);
                    memoryStream.Position = 0; // The position needs to be reset.

                    // prepare result to byte[]
                    result = memoryStream.ToArray();

                    var after = memoryStream.Length; // kind of not needed.
                    using(var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        memoryStream.CopyTo(fileStream);
                        await file.CopyToAsync(fileStream);
                    }


                    
                }

            }

            return Ok(new
            {
                location = filePath.Replace(HostingEnvironment.WebRootPath, "").Replace("\\", "/")
            });

        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
Lukas Hieronimus Adler
  • 1,063
  • 1
  • 17
  • 44
  • If you open the resulting image in an image editor, is the resolution correct? If you resave the image as a jpeg, how large is the size? i.e. is the resizing or the compression the problem? – JonasH Jan 26 '21 at 07:58

0 Answers0