c# - 如何将图像保存到文件系统?

标签 c# image

我正在尝试在 .exe 文件所在的目录中创建一个文件夹,并将图片保存在该文件夹中。

现在该文件夹不存在,所以我想创建。这是我的代码:

public void SavePictureToFileSystem(string path, Image picture)
{
    string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
    picture.Save(pictureFolderPath + "1.jpg");
}

图像没有保存到 pictureFolderPath 中,而是保存到路径变量中。我需要做什么才能做到这一点?

感谢您的帮助!这就是我最终得到的:

public void SavePictureToFileSystem(string path, Image picture)
{
    var pictureFolderPath = Path.Combine(path, ConfigurationManager.AppSettings["picturesFolderPath"].ToString());
    if (!Directory.Exists(pictureFolderPath))
    {
        Directory.CreateDirectory(pictureFolderPath);
    }

    picture.Save(Path.Combine(pictureFolderPath, "1.jpg"));
}

最佳答案

怀疑您的问题是 ConfigurationManager.AppSettings["picturesFolderPath"].ToString() 返回一个空的文件夹路径,或者更有可能不返回以尾部反斜杠结尾。这意味着最终构建的路径最终看起来像 c:\dir1.jpg 而不是 c:\dir\1.jpg,我认为你是这样的好想要。

无论如何,靠Path.Combine要好得多而不是尝试自己处理组合逻辑。它恰好处理这些类型的极端情况,此外,作为奖励,它与平台无关。

var appFolderPath = ConfigurationManager.AppSettings["picturesFolderPath"]
                                        .ToString();

// This part, I copied pretty much verbatim from your sample, expect
// using Path.Combine. The logic does seem a little suspect though.. 
// Does appFolder path really represent a subdirectory name?
var pictureFolderPath = Path.Combine(path, appFolderPath);

// Create folder if it doesn't exist
Directory.Create(pictureFolderPath);

// Final image path also constructed with Path.Combine
var imagePath = Path.Combine(pictureFolderPath, "1.jpg")
picture.Save(imagePath);

关于c# - 如何将图像保存到文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4087564/

相关文章:

c# - SQL 删除查询无法正常工作

c# - 从 C# 中的字典匹配正则表达式

c# - 如何安排在我的 MVC 网络应用程序中自动运行 Controller ?

android 快速像素访问和操作

html - 如何在没有另一个 div 的情况下让图像淡出

python - 如何使用OpenCV从图像中提取身份证件感兴趣区域?

c# - NAudio C#重采样发出麻烦

javascript - awesomium 网络抓取某些部分

python-3.x - 读取RGB原始输入,转换为openCV对象,然后转换为.JPEG字节-不带PIL

html - 如何将图片放入页脚标签中?