无法将图像保存在我创建的文件夹中

时间:2018-10-14 03:22:10

标签: c# file gdi+ openfiledialog imaging

我当前正在使用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可以正常工作,但resizedImages[k].Save会发出GDI +通用错误。 我认为是因为创建了文件夹,但找不到解决方案。

2 个答案:

答案 0 :(得分:1)

  

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

如果错误Directory.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方法,或者您正试图用打开的句柄覆盖文件。但是,本着我认为您要努力实现的精神,这可能会奏效

答案 1 :(得分:0)

问题是您正在尝试覆盖现有文件。 Image.Save方法不支持。

解决方案很简单,请先删除文件,然后再保存:

File.Delete(selectedFileName);
selectedImages[k].Save(selectedFileName, GetImageFormat(Path.GetExtension(fileNames[k])));