c# - 无法将图像保存在我创建的文件夹中
问题描述
我目前正在使用 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
工作得很好。我认为这是因为我创建的文件夹但我找不到解决方案。
解决方案
我认为这是因为我创建的文件夹但我找不到解决方案。
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
方法,或者您试图用打开的句柄覆盖文件。但是,本着我认为您正在努力实现的精神,这可能会奏效
推荐阅读
- android - ViewModel 检索空列表,但不应为空 (mutableStateOf)
- microsoft-graph-api - Microsoft Graph API:在创建私人频道时无法与所有者一起添加私人频道成员
- reactjs - React Material UI Select native - 未找到值时不显示为空
- flutter - 在颤动中为DataTable的DataRows添加边距
- amazon-ec2 - 消息:[/Resources/AWSEBCloudwatchAlarmHigh/Type/Dimensions/0/Value/Ref] 模板中不允许使用“null”值
- php - 在 WooCommerce 中显示不包括产品类别的订单项目名称
- python - 将数组从 c++ 返回到 python
- c++ - 单击或拖动标题栏时如何防止计时器冻结?
- android-studio - android studio中的gridlayout有问题
- benchmarking - 当我安装 SPEC2006 时,它不会执行此步骤