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

Resizing and creating image thumbnail in ASP.NET-Core 2.2

我正在尝试在 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.* 中创建图像缩略图以修复错误,请帮助我。

此致

错误来自缩略图的路径。 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 的父级 class 中包含以下 using 语句,如下所示:

using LazZiya.ImageResize;

同时,LazZiya.ImageResize 是用于管理 asp 中图像大小调整的 nugget 包。net-core 2.1 请参阅 github link Github link for LazZiya image nugget

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

此致

一次文件uploaded/saved到服务器。您可以使用以下 ASP.NET 核心中间件来提供图像缩略图。

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

在 startup.cs 中配置中间件并像下面那样传递缩略图大小:

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