我是C#的新手。我想从任何地方获取图像,在图片框中显示它,然后将其保存在同一文件夹(项目文件夹)中。但是它给出了错误。即“通用错误发生在GDI +中”。我已经看了很多帖子。但是我无法解决这个问题。我的代码如下。
private void btnImage_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bit = new Bitmap(open.FileName);
pictureBox1.Image = bit;
var imagestudent = pictureBox1.Image;
string extension = Path.GetFileNameWithoutExtension(open.FileName);
extension += DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + Path.GetExtension(open.FileName);
imagestudent.Save(@"PicturesofStudent\" + extension);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我该怎么办?
发生这种情况是因为您忘记了放在.
文件扩展名之前。试试这个
string extension = Path.GetFileNameWithoutExtension(open.FileName);
extension += DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + "." + Path.GetExtension(open.FileName);
编辑
您也可以尝试File.Copy而不是调用PictuteBox.Save
方法。:
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bit = new Bitmap(open.FileName);
pictureBox1.Image = bit;
var imagestudent = pictureBox1.Image;
string fileName = Path.GetFileNameWithoutExtension(open.FileName) +
DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") +
Path.GetExtension(open.FileName);
string directory = "PicturesofStudent";
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
File.Copy(open.FileName, Path.Combine(directory, fileName));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句