在ASP.NET-Core 2.2中调整大小并创建图像缩略图

时间:2019-06-14 13:52:31

标签: image-processing asp.net-core gdi+ asp.net-core-2.2 system.drawing.common

我正在尝试在asp.net-core 2.2应用程序中创建缩略图,但是每当它到达创建缩略图的位置时,我都会不断遇到上述错误。

主图像可以很好地创建和存储,但不能创建缩略图。请感谢任何解决错误的指南

这是我存储上传图像的方法。这一项工作符合预期

using LazZiya.ImageResize;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace eSchool.Models.Utilities
{
public  class FileUploadHelper
{
    private readonly IHostingEnvironment host;
    public FileUploadHelper(IHostingEnvironment _host)
    {
        host = _host;
    }

    public async Task<string> SaveFileAsync(IFormFile file, string pathToUplaod)
    {
        string webroot=host.WebRootPath;

        string DesiredDirectoryLocation = Path.Combine(webroot,pathToUplaod);
        if(!Directory.Exists(DesiredDirectoryLocation))
        {
            Directory.CreateDirectory(DesiredDirectoryLocation);
        }

        string imageUrl = string.Empty;
        var filename = Path.GetRandomFileName();
        var newfilename = CreateUniqueFileName(file);
        string pathwithfileName = DesiredDirectoryLocation + "/" + newfilename;
        using (var fileStream = new FileStream(pathwithfileName, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }

        imageUrl = newfilename;

        return imageUrl;
    }

我尝试了两种不同的方法来创建缩略图,但是其中任何一种都会产生上述错误

这是两种方法。

第一个是这个:

public string CreateThumbImage(IFormFile uploadedFile, string desiredThumbPath,string desiredThumbFilename, int desiredThumbWidth, int desiredThumbHeight)
    {
        try
        {
            Stream filestream = uploadedFile.OpenReadStream();
            Image thumbnailStream = Image.FromStream(filestream);
            Image thumbnailImage = thumbnailStream.GetThumbnailImage(desiredThumbWidth, desiredThumbHeight, () => false, IntPtr.Zero);

            string webroot = host.WebRootPath;

            string DesiredDirectoryLocation = Path.Combine(webroot, desiredThumbPath);

            if (!Directory.Exists(DesiredDirectoryLocation))
            {
                Directory.CreateDirectory(DesiredDirectoryLocation);
            }

            string thumbFullPathName = desiredThumbPath + "/" + desiredThumbFilename;
            thumbnailImage.Save(thumbFullPathName);

            return thumbFullPathName;
        }
        catch
        {
            throw;
        }

    }

第二个是这个

public void ResizeImage(IFormFile uploadedFile, string desiredThumbPath, int desiredWidth=0, int desiredHeight=0)
    {
        if (uploadedFile.Length > 0)
        {
            using (var stream = uploadedFile.OpenReadStream())
            {
                var uploadedImage = System.Drawing.Image.FromStream(stream);

                //decide how to scale dimensions
                if (desiredHeight == 0 && desiredWidth > 0)
                {
                    var img = ImageResize.ScaleByWidth(uploadedImage, desiredWidth); // returns System.Drawing.Image file
                    img.SaveAs(desiredThumbPath);
                }
                else if(desiredWidth == 0 && desiredHeight > 0)
                {
                    var img = ImageResize.ScaleByHeight(uploadedImage, desiredHeight); // returns System.Drawing.Image file
                    img.SaveAs(desiredThumbPath);
                }
                else
                {
                    var img = ImageResize.Scale(uploadedImage, desiredWidth,desiredHeight); // returns System.Drawing.Image file
                    img.SaveAs(desiredThumbPath);
                }

            }
        }
        return;
    }

这是我调用方法的地方:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {

        FileUploadHelper uploadHelper = new FileUploadHelper(_host);
        if (EmailValidation.EmailExists(model.EmailAddress,_context))
        {
            ModelState.AddModelError("EmailAddress", "This email address is already registered with us.");
        }

        if (model.Photo != null)
        {
            string[] extensions = new string[] { ".jpeg",".jpg", ".gif", ".png" };

            ///Validate the type of the image file being uploaded
            ResponseMsg fileTypeValidated = uploadHelper.ValidateFileExtension(model.Photo, extensions);
            if (!fileTypeValidated.ResponseStatus)
            {
                ModelState.AddModelError("Photo", fileTypeValidated.ResponseDescription);
            }

            ///Validate the size of the image file being uploaded
            ResponseMsg fileSizeValidated = uploadHelper.ValidateFilesize(model.Photo, 1);
            if (!fileSizeValidated.ResponseStatus)
            {
                ModelState.AddModelError("Photo", fileSizeValidated.ResponseDescription);
            }
        }

        if (ModelState.IsValid)
        {
            try
            {
                Instructor instructor = new Instructor
                {
                    Surname = model.Surname,
                    OtherNames = model.Othernames,
                    Email = model.EmailAddress,
                    UserName = model.EmailAddress,
                    PhoneNumber = model.PhoneNumber,
                    Gender = model.Gender,
                    StateId = model.ResidenceState,
                    LgaId = model.ResidenceLga,
                    DateOfBirth = model.DateOfBirth,
                    TimeRegistered = DateTime.Now
                };

                var photo = await uploadHelper.SaveFileAsync(model.Photo,"images/instructors");
                //Create image thumbnail for the instructor photo
                var photo_thumbnail = "images/instructors/thumbs/" + photo;
                uploadHelper.CreateThumbImage(model.Photo, "images/instructors/thumbs/", photo, 100, 100);...

如果您能指出我缺少正确的路径或在ASP.NET-Core 2. *中处理图像缩略图创建的更好方法来解决此错误,请提供帮助。

致谢

2 个答案:

答案 0 :(得分:1)

错误来自缩略图的路径。 ResizeImage方法中给出的路径并不表示缩略图的文件名。这就是通用GDI +错误的来源。

因此,当将调整大小后的图像的路径(包括图像文件名)正确地传递到 SaveAs 方法时,使用ResizeImage方法即可。这是工作方法:

public void ResizeImage(IFormFile uploadedFile, string desiredThumbPath, int desiredWidth=0, int desiredHeight=0)
    {
        string webroot = host.WebRootPath;

        if (uploadedFile.Length > 0)
        {
            using (var stream = uploadedFile.OpenReadStream())
            {
                var uploadedImage = System.Drawing.Image.FromStream(stream);

                //decide how to scale dimensions
                if (desiredHeight == 0 && desiredWidth > 0)
                {
                    var img = ImageResize.ScaleByWidth(uploadedImage, desiredWidth); // returns System.Drawing.Image file
                    img.SaveAs(Path.Combine(webroot,desiredThumbPath));
                }
                else if(desiredWidth == 0 && desiredHeight > 0)
                {
                    var img = ImageResize.ScaleByHeight(uploadedImage, desiredHeight); // returns System.Drawing.Image file
                    img.SaveAs(Path.Combine(webroot,desiredThumbPath));
                }
                else
                {
                    var img = ImageResize.Scale(uploadedImage, desiredWidth,desiredHeight); // returns System.Drawing.Image file
                    img.SaveAs(Path.Combine(webroot,desiredThumbPath));
                }
            }
        }
        return;
    }

实现如下:

//Create image thumbnail for the instructor photo
                var photo_thumbnail = "images/instructors/thumbs/" + photo;
                uploadHelper.ResizeImage(model.Photo, photo_thumbnail, 100);

请记住,在包含ResizeImage方法的uploadHelper父类中包含以下using语句:

using LazZiya.ImageResize;

同时,LazZiya.ImageResize是用于管理asp.net-core 2.1中图像大小调整的块包。 查看它的github链接Github link for LazZiya image nugget

因此,这解决了asp.net-core中的图像大小调整问题

致谢

答案 1 :(得分:0)

一旦文件上传/保存到服务器。您可以使用以下ASP.NET核心中间件来提供图像缩略图。

https://github.com/osprakash/ImageThumbnail-aspnetcore

在startup.cs中配置中间件并传递缩略图大小,如下所示:

免责声明:我是上述开源软件包的作者。