代码之家  ›  专栏  ›  技术社区  ›  Arunprasanth K V

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

  •  0
  • Arunprasanth K V  · 技术社区  · 7 年前

    我需要从原始图像创建一个缩略图图像,并需要将这两个图像保存在本地文件夹中。 我正在使用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();
            }
        }
    }
    

    在这里,我需要特定图像的缩略图

    到目前为止,我尝试的是添加 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 所以我也不能直接给出路径。

    1 回复  |  直到 7 年前
        1
  •  21
  •   David Noreña    5 年前

    终于得到了答案

    安装 System.Drawing.Common -Version 4.5.1 包裹

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

    安装软件包System.Drawing.Common-版本5.0.2

    然后使用以下代码:

    using System.Drawing;
    
    var stream = ProductImage.OpenReadStream();
    
    var newImage = GetReducedImage(32,32,stream);
    newImage.Save("path+filename");
    
    public Image GetReducedImage(int width, int height, Stream resourceImage)
    {
        try
        {
            var image = Image.FromStream(resourceImage);
            var thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);
    
            return thumb;
        }
        catch (Exception e)
        {
            return null;
        }
    }