如何在.net核心中创建缩略图?使用IFormFile的帮助

问题描述 投票:1回答:1

我需要从原始图像创建缩略图图像,并需要将这两个图像保存在本地文件夹中。我使用html文件控件上传图像

   <input type="file" class="form-control" asp-for="ImageName" name="ProductImage" id="ProductImage">

到表单提交时,我将它作为IFromFile

       [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Guid id, ProductDTO product, IFormFile 
        ProductImage)
        {
            if (ModelState.IsValid)
            {
                byte[] fileBytes;
                using (var ms = new MemoryStream())
                {
                    ProductImage.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }
            }
        }

我已将其转换为byte []并将其传递给我的一个保存方法。在这里,我需要特定图像的缩略图

我到目前为止尝试的是添加package Install-Package System.Drawing.Common -Version 4.5.1

并创建了一种转换图像的方法

 public string ErrMessage;

        public bool ThumbnailCallback()
        {
            return false;
        }
        public Image GetReducedImage(int Width, int Height, Image ResourceImage)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

但我创建的方法是接受一种Image这里有点困惑,不知道我们怎么能用byte[]做到这一点。另外,我没有从IFileForm获取图像本地路径,所以我不能直接给出路径。

有人可以帮我解决这个问题吗?

c# image-processing .net-core asp.net-core-mvc thumbnails
1个回答
4
投票

终于得到了答案

安装System.Drawing.Common -Version 4.5.1

打开包管理器并运行以下代码以安装包

Install-Package System.Drawing.Common -Version 4.5.1

Then use the below code 

 Stream stream=ProductImage.OpenReadStream();

Image newImage=GetReducedImage(32,32,stream);
newImage.Save("path+filename");

public Image GetReducedImage(int width, int height, Stream resourceImage)
        {
            try
            {
                Image image = Image.FromStream(resourceImage);
                Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);

                return thumb;
            }
            catch (Exception e)
            {
                return null;
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.