C# 无法将图像保存在我创建的文件夹中
我目前正在用C#Windows窗体创建一个图像大小调整程序。 所以,我让它覆盖现有的图像与调整大小的图像。 我还制作了一个函数,可以创建C# 无法将图像保存在我创建的文件夹中,c#,file,gdi+,openfiledialog,imaging,C#,File,Gdi+,Openfiledialog,Imaging,我目前正在用C#Windows窗体创建一个图像大小调整程序。 所以,我让它覆盖现有的图像与调整大小的图像。 我还制作了一个函数,可以创建Originals文件夹并将原始图像保存在其中,以便在需要原始图像时可以使用文件夹中的图像。 下面是第 for (int k = 0; k < openFileDialog.FileNames.Length; k++) { fileNames.Add(openFileDialog.FileNames[k]); using (Stream st
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);
}
for(int k=0;k
这里的问题是selectedImages[k].Save
emit GDI+一般错误,尽管resizedImages[k].Save
工作完全正常。
我想这是因为我创建的文件夹,但我找不到解决方案
我想这是因为我创建了一个文件夹,但我找不到一个
解决方案
如果它不能在不存在的情况下创建异常,则错误将抛出异常
因此,让我们来解决您的问题
不要这样做,如果需要反斜杠,请使用@\\Originals\\
\Originals\
- 如果要合并路径,请使用
- 如果可以使用
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
方法,或者您试图用打开的句柄覆盖文件。然而,本着我认为您正在努力实现的精神,这可能只会起作用问题是您试图覆盖现有文件。Image.Save方法不支持此操作
解决方案很简单,请在再次保存之前删除该文件:
File.Delete(selectedFileName);
selectedImages[k].Save(selectedFileName, GetImageFormat(Path.GetExtension(fileNames[k])));