在产品页面的 ASP.NET 核心 mvc 上使用 Sixlabour.ImageSharper

Using Sixlabour.ImageSharper on ASP.NET Core mvc on Product Page

在我的项目产品页面控制器中,我想上传一张图片并在提交图片后自动压缩,所以我使用了Sixlabour.ImageSharper。它在我的演示项目中工作(我只添加一个输入字段图像)。当我在我的主项目中移动这段代码时,它不起作用。

这是我的代码:

ProductController.cs

public string ResizeImage(Image img, int maxWidth, int maxHeight)
{
        if (img.Width > maxWidth || img.Height > maxHeight)
        {
            double widthRatio = (double)img.Width / (double)maxWidth;
            double heightRatio = (double)img.Height / (double)maxHeight;
            double ratio = Math.Max(widthRatio, heightRatio);
            int newWidth = (int)(img.Width / ratio);
            int newHeight = (int)(img.Height / ratio);
            return newHeight.ToString() + "," + newWidth.ToString();
        }
        else
        {
            return img.Height.ToString() + "," + img.Width.ToString();
        }
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upsert(ProductVM productVM,IFormFile file)
{
        if (ModelState.IsValid)
        {
            string webRootPath = _hostEnvironment.WebRootPath;
            var files = HttpContext.Request.Form.Files;

            if (files.Count > 0)
            {
                string fileName = Guid.NewGuid().ToString();
                var uploads = Path.Combine(webRootPath, @"images\products");
                var extension = Path.GetExtension(files[0].FileName);
                
                using (var image = Image.Load(file.OpenReadStream()))
                {
                    string newSize = ResizeImage(image, 500, 500);
                    string[] aSize = newSize.Split(',');
                    image.Mutate(h => h.Resize(Convert.ToInt32(aSize[1]), Convert.ToInt32(aSize[0])));
                }
                
                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 + extension), FileMode.Create))
                {
                    files[0].CopyTo(filesStreams);
                }

                productVM.Product.ImageUrl = @"\images\products\" + fileName + extension;
            }
            else
            {
                //update when they do not change the image
                if(productVM.Product.Id != 0)
                {
                    Product objFromDb = _unitOfWork.Product.Get(productVM.Product.Id);
                    productVM.Product.ImageUrl = objFromDb.ImageUrl;
                }
            }


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

            }
            else
            {
                _unitOfWork.Product.Update(productVM.Product);
            }
            _unitOfWork.Save();
            return RedirectToAction(nameof(Index));
        }
        
        return View(productVM);
    }
I used webrootpath for uploading images.how can I solve this
**Error** show "Object reference not set to an instance of an object" on using (var image = Image.Load(file.OpenReadStream()))

我自己解决了 这是解决方案..我删除了 webRoot 路径,然后手动调用它

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Upsert(ProductVM productVM, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count > 0)
                {
                    string fileName = string.Empty;
                    string path = string.Empty;
                    if (file.Length > 0) //that means file was uploaded
                    {
                        fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                        path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/products"));
                        string fullPath = Path.Combine(path, fileName);
                        using (var image = Image.Load(file.OpenReadStream()))
                        {
                            string newSize = ResizeImage(image, 500, 500);
                            string[] aSize = newSize.Split(',');
                            image.Mutate(h => h.Resize(Convert.ToInt32(aSize[1]), Convert.ToInt32(aSize[0])));
                            image.Save(fullPath);
                        }

                        if(productVM.Product.Id != 0 )
                        {
                            Product objFromDb = await _unitOfWork.Product.GetAsync(productVM.Product.Id);
                            productVM.Product.ImageUrl = objFromDb.ImageUrl;

                            if(objFromDb.ImageUrl!= null)
                            {
                                //Image already exists we need to remove old image
                                var imagepath = Path.Combine(Directory.GetCurrentDirectory(), objFromDb.ImageUrl.TrimStart('\'));
                                if (System.IO.File.Exists(imagepath))
                                    System.IO.File.Delete(imagepath);
                            }
                        }

                        productVM.Product.ImageUrl = @"\images\products\" + fileName;

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

        public string ResizeImage(Image img, int maxWidth, int maxHeight)
        {
            if (img.Width > maxWidth || img.Height > maxHeight)
            {
                double widthRatio = (double)img.Width / (double)maxWidth;
                double heightRatio = (double)img.Height / (double)maxHeight;
                double ratio = Math.Max(widthRatio, heightRatio);
                int newWidth = (int)(img.Width / ratio);
                int newHeight = (int)(img.Height / ratio);
                return newHeight.ToString() + "," + newWidth.ToString();
            }
            else
            {
                return img.Height.ToString() + "," + img.Width.ToString();
            }
        }