【问题标题】:How to write image in specific folder如何在特定文件夹中写入图像
【发布时间】:2021-07-21 18:18:00
【问题描述】:

我正在尝试在我的项目的特定目录中添加个人资料图片:~Images/ProfilePicture

_context.People.Add(person);
                _context.SaveChanges();
                if (person.ProfilePicture != null)
                {
                    string[] photoName = person.ProfilePicture.FileName.Split('.');
                    var imageName = $"{person.PersonId}.{photoName[photoName.Length - 1]}";
                    string uploaded = Path.Combine("~Images", "ProfilePicturePerson");
                    string filepath = Path.Combine(uploaded, imageName);

                    //return MagickImage
                    var profilePic = ImageStuff.HandleImage(person.ProfilePicture);
                    //error
                    profilePic.Write(imageName);
                    person.ProfilePictureName = filepath;
                }
                
                _context.SaveChanges();

我希望MagickImage.write函数在指定目录下创建文件,而不是在项目主目录下创建图片

【问题讨论】:

    标签: c# asp.net-core .net-core imagemagick


    【解决方案1】:

    你应该像这样在你的服务中引入 IHostEnvironment:

        public class Service : IService
        {
            private readonly IHostEnvironment _environment;
            
            public SftpService(IHostEnvironment environment)
            {   
                _environment = environment;
            }
    
            public void DownloadFile()
            {
                 var _fileName = "PictureName";
                 var remoteFilePath= "Path where is your image";
    
                 //if your service is in your main proyect
                 var localFilePath = Path.Combine($" 
                 {_environment.ContentRootPath}\\Images\\ProfilePicture\\             
                 {_fileName}");
    
                 //if your service is in your other proyect. For example Application
                 var localFilePath = 
                 Path.Combine(_environment.ContentRootPath.Replace("MS.Core", 
                 "MS.Aplication"), $"\\Images\\ProfilePicture\\{_fileName}");
    
                 try
                    {
                       client.Connect();
                       using var s = File.Create(localFilePath);
    
                       client.DownloadFile(remoteFilePath, s);
                    }
                    catch (Exception exception)
                    {
    
                    }
                    finally
                    {
                       client.Disconnect();
                    }
            }
        }
    

    此示例假设图像在某些外部服务中,但您或许可以将其作为指导。

    【讨论】:

    • 我注入了IHostEnvironment,我可以得到图像,但我必须调整它的大小并压缩它,然后重写文件,当它重写时,它将它保存在根路径上,不像我想将它保存在项目的另一个文件夹中。
    • 您是否在 localPath 变量中写入了正确的路径??
    • 这里的东西是没有办法设置路径,就是放在根路径下
    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多