首页 > 解决方案 > 在 .NET CORE MVC 中压缩图像

问题描述

我开发了一个带有图像上传的网络应用程序。用户可以上传各种图像尺寸的各种图像(jpg、png、...)。目前图像大小在 1MB 到 6MB 之间。使用 API 可以读取图像,但存在问题。它非常慢,因为图像的大小太大。

现在我想将图像大小压缩到最大 300KB - 500KB。我尝试了可以​​调整图像大小的库 SixLabors.ImageSharp。但是图像文件仍然是相同数量的 MB 大。

有人可以为我提供减小图像大小的解决方案吗?

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);
        }
    }

标签: c#.net-corefile-uploadasp.net-core-mvc

解决方案


推荐阅读