我正在尝试保存像bmp,jpg,gif和amp; png进入sql server数据库。但无法将所有格式保存到数据库中。只有png图像被保存到数据库中。如果试图保存jpeg,.bmp& .gif图片,它显示错误" GDI +"中出现一般错误。有什么问题?
private void InitializeOpenFileDialog()
{
try
{
this.openFileDialog1 = new OpenFileDialog();
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" + "All files (*.*)|*.*";
//"image files|*.jpg;*.png;*.gif;*.bmp;.*;";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
//load picture
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
// byte[] img_arr1 = ms1.ToArray();
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
SqlConnection con = new SqlConnection(@"data source=xdfgh\ALEXDAVE;database=x1234;UID=sa;password=x67890");
con.Open();
SqlCommand cmd = new SqlCommand("insert into myTable(enrolmentno,aadhaarno,name,fname,address,dob,gender,picimage)values(@a,@b,@c,@d,@e,@f,@g,@h)", con);
cmd.Parameters.AddWithValue("@a", enrolmentno_txt.Text);
cmd.Parameters.AddWithValue("@b", aadhaarno_txt.Text);
cmd.Parameters.AddWithValue("@c", name_txt.Text);
cmd.Parameters.AddWithValue("@d", fname_txt.Text);
cmd.Parameters.AddWithValue("@e", address_txt.Text);
cmd.Parameters.AddWithValue("@f", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("@g", gender);
cmd.Parameters.AddWithValue("@h", img_arr1);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Data inserted successfully");
else
MessageBox.Show("Data is not inserted in database");
con.Close();
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.Activate();
string[] files = openFileDialog1.FileNames;
try
{
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileStream fileStream = fileInfo.OpenRead();
pictureBox2.Image = Image.FromStream(fileStream);
Application.DoEvents();
fileStream.Close();
}
}
//es
catch (Exception)
{
MessageBox.Show("please select only image files.");
}
}
答案 0 :(得分:0)
你确定图像有效吗? 您收到错误的是哪一行? 与错误指示一样,它是GDI错误,而不是SQL错误。
您可以通过替换以下代码行来删除对GDI的需求
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
用这个
byte[] img_arr1 = System.IO.File.ReadAllBytes(fileName);
其中fileName是已选择的文件