首页 > 解决方案 > 无法将图像保存在我创建的文件夹中

问题描述

我目前正在使用 C# Windows 窗体创建一个图像大小调整程序。所以,我让它用调整大小的图像覆盖现有图像。我还制作了一个创建Originals文件夹并将原始图像保存在其中的功能,以便当我需要原始图像时可以使用文件夹中的图像。下面是

for (int k = 0; k < openFileDialog.FileNames.Length; k++)
{
   fileNames.Add(openFileDialog.FileNames[k]);

   using (Stream stream = File.OpenRead(fileNames[k]))
   {
       //System.Collections.Generic.List<System.Drawing.Image>
       selectedImages.Add(Image.FromStream(stream));
       resizedImages.Add(Image.FromStream(stream));                                                 
   }
   filesCount++;
}

for (int k = 0; k < filesCount; k++)
{
    string filePath = Path.GetDirectoryName(fileNames[k]);
    Directory.CreateDirectory(filePath + "\\Originals");

    string selectedFileName = filePath + "\\Originals\\" + Path.GetFileName(fileNames[k]);
    string resizedFileName = filePath + "\\" + Path.GetFileNameWithoutExtension(fileNames[k]) + ".jpg";

    //GetImageFormat is my function that return ImageFormat. It has no problem.
    selectedImages[k].Save(selectedFileName, GetImageFormat(Path.GetExtension(fileNames[k])));
    resizedImages[k].Save(resizedFileName, ImageFormat.Jpeg);
}

这里的问题是selectedImages[k].Save发出 GDI+ 通用错误虽然resizedImages[k].Save工作得很好。我认为这是因为我创建的文件夹但我找不到解决方案。

标签: c#filegdi+openfiledialogimaging

解决方案


我认为这是因为我创建的文件夹但我找不到解决方案。

WrongDirectory.CreateDirectory如果在它不存在的情况下无法创建它,则会抛出异常。


因此,让我们解决您遇到的问题

  • \\Originals\\不要这样做,如果您需要反斜杠,请使用 @\Originals\
  • 如果要组合路径,请使用Path.Combine
  • for可以使用时不要使用foreach
  • 没有必要制作这么多列表和循环
  • 如果您创建图像,则需要处理它
  • 最重要的是,不要尝试将文件保存在具有打开文件句柄的文件上。

在这种情况下,您需要退出代码并删除所有冗余。绝对不需要您的大部分代码,这使您的生活更难调试

foreach (var file in openFileDialog.FileNames)
{
   var name = Path.GetFileName(file);
   var path = Path.GetDirectoryName(file);
   var newPath = Path.Combine(path, "Originals");
   var newName = $"{Path.GetFileNameWithoutExtension(name)}.jpg";

   Directory.CreateDirectory(newPath);

   var newFullPath = Path.Combine(newPath, name);
   // why do anything fancy when you just want to move it
   File.Move(file, newFullPath);

   // lets open that file from there, so we don't accidentally cause the same 
   // problem again, then save it
   using (var image = Image.FromFile(newFullPath))
      image.Save(Path.Combine(path, newName), ImageFormat.Jpeg);  
}

虽然我不确定您的实际问题是什么,但我假设它是GetImageFormat方法,或者您试图用打开的句柄覆盖文件。但是,本着我认为您正在努力实现的精神,这可能会奏效


推荐阅读