ASP.NET Core - 如何同时压缩和调整图像和质量

ASP.NET Core - How to Compress and Resize image and quality also

在我的大学电子商务画廊项目中,我想在上传图像时自动压缩图像的大小,就像上传后图像大小为 2mb 一样,它会变成 600 kb 或 400kb 那么如何做到这一点..我的代码在下面..

ProductController.cs

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Upsert(ProductVM productVM)
        {
            if (ModelState.IsValid)
            {
                string webRootPath = _hostEnvironment.WebRootPath; //getting image Path
                var files = HttpContext.Request.Form.Files; //Retrive all the files that are uploaded
                if(files.Count > 0) //that means file was uploaded
                {
                    string fileName = Guid.NewGuid().ToString();
                    var uploads = Path.Combine(webRootPath, @"images\products");
                    var extenstion = Path.GetExtension(files[0].FileName);

                    if (productVM.Product.ImageUrl != null)
                    {
                        //this is an edit and we need to remove old image
                        var imagePath = Path.Combine(webRootPath, 
                        productVM.Product.ImageUrl.TrimStart('\'));
                        if (System.IO.File.Exists(imagePath))
                        {
                            System.IO.File.Delete(imagePath);
                        }
                    }
                    using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + 
                    extenstion), FileMode.Create))
                    {
                        files[0].CopyTo(filesStreams);
                    }
                    productVM.Product.ImageUrl = @"\images\products\" + fileName + extenstion;
                }
                else
                {
                    //update when they do not change the image
                    if (productVM.Product.Id != 0)
                    {
                        Product objFromDb = await _unitOfWork.Product.GetAsync(productVM.Product.Id);
                        productVM.Product.ImageUrl = objFromDb.ImageUrl;
                    }
                }

                if (productVM.Product.Id == 0)
                {
                   await _unitOfWork.Product.AddAsync(productVM.Product);

                }
                else
                {
                    _unitOfWork.Product.Update(productVM.Product);
                }
                _unitOfWork.Save();
                return RedirectToAction(nameof(Index));

            }
           ..
           ..
           ..
            return View(productVM);
        }

Upsert.cshtml

<section>
    <div class="container-lg pt-4">
        <form method="post" enctype="multipart/form-data">
            <div class="row p-3 border">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                
                <div class="col-8 pt-4">
                    <div class="form-group row">
                        <div class="col-4">
                            <label asp-for="Product.Title"></label>
                        </div>
                        <div class="col-8">
                            <input asp-for="Product.Title" class="form-control" />
                            <span asp-validation-for="Product.Title" class="text-danger"></span>
                        </div>
                    </div>
                    
                    <div class="form-group row">
                        <div class="col-4">
                            Image
                        </div>
                        <div class="col-8">
                            <input type="file" name="files" id="uploadBox" multiple class="form-control" 
                             />
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-8 offset-4">
                            @if (Model.Product.Id != 0)
                            {
                                <partial name="_EditAndBackToListButton" model="Model.Product.Id" />
                            }
                            else
                            {
                                <div class="row">
                                    <div class="col">
                                        <button type="submit" class="btn btn-primary form-control">Create</button>
                                    </div>
                                    <div class="col">
                                        <button asp-action="Index" class="btn btn-success form-control">Back To List</button>
                                    </div>
                                </div>

                            }
                        </div>
                    </div>
                </div>
                
            </div>
        </form>
    </div>

有没有压缩图片大小的nuget包

是的,你可以使用这个:https://github.com/omuleanu/imager 所以它会是这样的:

Image img = Imager.Resize(sourceImage, newWidth, maxHeight);

如果你想在上传后在服务器上调整它的大小,但你也可以在上传前调整它的大小,如这个演示网站所示: https://prodinner.aspnetawesome.com/Meal

尝试在“更改图片”后点击任何项目上的编辑 为此,使用 cropper.js 和 dropzone.js。

https://fengyuanchen.github.io/cropperjs/ https://www.dropzonejs.com/

你可以看看这个demo,经过测试,它可以把65KB的图片变成15KB的图片:

您只需要发送压缩级别为0~100的源图像位置,以及发送到哪里

压缩图片。

public IActionResult Index()
    {
        string filename = @"C:\*****\Saved Pictures\dog.jpg"; //source image location
        Bitmap img = new Bitmap(filename);   //image to bitmap                 
        var name = "result.jpg";  //your output image name
        Compress(img, @"C:\****\wwwroot\images\"+name, 0); //level 0~100, 0 is the worst resolution
        return View();
    }

    public static void Compress(Bitmap srcBitMap, string destFile, long level)
    {
        Stream s = new FileStream(destFile, FileMode.Create); //create FileStream,this will finally be used to create the new image 
        Compress(srcBitMap, s, level);  //main progress to compress image
        s.Close();
    }

    private static ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }
    private static void Compress(Bitmap srcBitmap, Stream destStream, long level)
    {
        ImageCodecInfo myImageCodecInfo;
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;
        myImageCodecInfo = GetEncoderInfo("image/jpeg");
        myEncoder = Encoder.Quality;
        myEncoderParameters = new EncoderParameters(1);
        myEncoderParameter = new EncoderParameter(myEncoder, level);
        myEncoderParameters.Param[0] = myEncoderParameter;
        srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
    }

结果(前后对比):