首页 > 解决方案 > 在 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.* 中处理图像缩略图创建的更好方法以修复错误,请帮助我。

问候

标签: asp.net-coreimage-processinggdi+system.drawing.common

解决方案


错误来自缩略图的路径。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 中管理图像大小调整的 nugget 包,请参阅 github 链接LazZiya 图像块的 Github 链接

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

问候


推荐阅读