使用 Sysytem.Drawing.Image 的 ASP.NET CORE MVC

我尝试使用 System.Drawing.Image 在 ASP.NET Core MVC 中保存图像,但出现此错误A generic error occurred in GDI+,并且不知道如何修复它。

我在这行代码中收到错误: newImg.Save(_hostingEnvironment.ContentRootPath, img.RawFormat);位于方法中SaveToFolder

这是我的 IRepository 中的所有代码:

   using System;

    using System.Collections.Generic;

    using System.Drawing;

    using System.IO;

    using System.IO.Compression;

    using System.Linq;

    using System.Net.Mime;

    using System.Threading.Tasks;

    using AstroPhotoWebSite_v3.Data;

    using AstroPhotoWebSite_v3.Interfaces;

    using AstroPhotoWebSite_v3.Models;

    using Microsoft.AspNetCore.Hosting;

    using Microsoft.AspNetCore.Http;



    namespace AstroPhotoWebSite_v3.Repositories

    {

        public class GalaxysRepository : IRepository<GalaxysModel>

        {

            private readonly ApplicationDbContext _context;

            private readonly IHostingEnvironment _hostingEnvironment;

            private ApplicationDbContext context;


            public GalaxysRepository(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)

            {

                this.context = _context;

                _hostingEnvironment = hostingEnvironment;

            }


            public List<GalaxysModel> Entities => _context.Galaxys.ToList();


            private Size NewImageSize(Size imageSize, Size newSize)

            {

                Size finalSize;

                double tempval;

                if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)

                {

                    if (imageSize.Height > imageSize.Width)

                    {

                        tempval = newSize.Height / (imageSize.Height * 1.0);

                    }

                    else


猛跑小猪
浏览 114回答 1
1回答

牧羊人nacy

我记得我也遇到过同样的问题,当您尝试保存图像的文件夹在物理路径中不存在时,通常会发生这种情况,因此请尝试创建该文件夹并重试,否则您必须创建该文件夹如果不存在使用以下代码:&nbsp; &nbsp; &nbsp; &nbsp; Image image = Image.FromStream(stream);&nbsp; &nbsp; &nbsp; &nbsp; string folderName = @"YourFolderPath";&nbsp; &nbsp; &nbsp; &nbsp; string path = Path.Combine(_hostingEnvironment.ContentRootPath, folderName);&nbsp; &nbsp; &nbsp; &nbsp; bool exists = Directory.Exists(path);&nbsp; &nbsp; &nbsp; &nbsp; if (!exists)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Directory.CreateDirectory(path);&nbsp; &nbsp; &nbsp; &nbsp; image.Save(path);&nbsp; &nbsp; &nbsp; &nbsp; image.Dispose();&nbsp; &nbsp; &nbsp; &nbsp; stream.Dispose();我建议在您的 SaveToFolder 函数中使用它,但是,因为我可以看到您已经在图像路径中添加了文件夹路径,您应该将其与函数一起传递,或者在创建函数中进行此检查。
打开App,查看更多内容
随时随地看视频慕课网APP