将图像存储在 C# 窗口窗体应用中的同一文件夹中

本文关键字:文件夹 应用 窗体 存储 图像 窗口 | 更新日期: 2023-09-27 18:34:55

我是C#的新手。我想在任何地方获取图像,将其显示在图片框中,然后将其保存在同一文件夹(项目文件夹(中。但它给出了错误 .i.e "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);
        }
    }

我该怎么办?

将图像存储在 C# 窗口窗体应用中的同一文件夹中

发生这种情况是因为您忘记将.放在文件扩展名之前。试试这个

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));
}