我使用图片框来编辑图像,并使用文件保存对话框来保存图像。
我遇到的问题是,无论我选择什么文件格式,文件都会保存为位图。我在这里做了一些研究并尝试进行一些更改,但它们不起作用。该对话框尝试保存文件 5 次,然后失败。我的感觉是我没有成功选择文件格式/文件扩展名。
我正在尝试几种不同的方法,但它们不起作用。我已经在此处阅读了堆栈溢出,我应该使用(
Path.GetExtension(save.FileName)
),但编译器拒绝Path.GetExtension
(路径在当前上下文中不存在)。这是我的代码,如果有人能指出我的错误所在,我将不胜感激。
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Bitmap files (*.bmp)|*.bmp|JPG files (*.jpg)|*.jpg|GIF files (*.gif)|*.gif|PNG files (*.png)|*.png|TIF files (*.tif)|*.tif|All files (*.*)|*.*";
save.FilterIndex = 4;
save.RestoreDirectory = true;
save.OverwritePrompt = true;
save.ShowHelp = true;
save.AddExtension = true;
if (save.ShowDialog() == DialogResult.OK && save.FilterIndex == 1)
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
if (save.ShowDialog() == DialogResult.OK && save.FileName.Substring(save.FileName.Length - 4) == ".jpg")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
if (save.ShowDialog() == DialogResult.OK && save.FileName.Substring(save.FileName.Length - 3) == "gif")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Gif);
if (save.ShowDialog() == DialogResult.OK && save.FileName.Substring(save.FileName.Length - 3) == "png")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Png);
if (save.ShowDialog() == DialogResult.OK && save.FileName.Substring(save.FileName.Length - 3) == "tif")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Tiff);
else
MessageBox.Show("File Save Error.");
}
另外,有没有办法访问 C# 中的文件保存选项(例如,jpg 中的子采样或 gif 中的抖动)?
谢谢你
只是想发布对其他提出同样问题的人有用的内容。感谢以上大家的帮助。
using system.IO;
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Bitmap files (*.bmp)|*.bmp|JPG files (*.jpg)|*.jpg|GIF files (*.gif)|*.gif|PNG files (*.png)|*.png|TIF files (*.tif)|*.tif|All files (*.*)|*.*";
save.FilterIndex = 2;
save.RestoreDirectory = true;
save.OverwritePrompt = true;
save.ShowHelp = true;
save.AddExtension = true;
if ((save.ShowDialog() == DialogResult.OK)) {
if (Path.GetExtension(save.FileName).ToLower() == ".bmp")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
else if (Path.GetExtension(save.FileName).ToLower() == ".jpg")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
else if (Path.GetExtension(save.FileName).ToLower() == ".gif")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Gif);
else if (Path.GetExtension(save.FileName).ToLower() == ".png")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Png);
else if (Path.GetExtension(save.FileName).ToLower() == ".tif")
pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Tiff);
else
MessageBox.Show("File Save Error.");
}
由于某种原因,PNG 保存的大小比 TIF 稍大,PNG 应该小 33% 左右,我怀疑这是 Visual Studio PNG 实现的问题。对于任何对真正小型 PNG 感兴趣的人,有一个名为 PNGcrush 的开源控制台应用程序。