我无法在数据库中插入图片。这是我的示例代码。我可以从我的电脑中选择一个图像并显示在图片框中。我试图将图片框中显示的图像存储到数据库中表示对象引用未设置为对象的实例。
这是我的示例代码。
namespace picutre_storage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection
(@"User ID=sa;Password=password123;Initial Catalog=picuture;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
//I have used a table named "tblUsers" and fill the fields
SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", con);
//Save image from PictureBox into MemoryStream object.
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,ImageFormat.Bmp);
//Read from MemoryStream into Byte array.
Byte[] bytBLOBData = new Byte[ms.Length];
ms.Position = 0;
ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));
//Create parameter for insert statement that contains image.
SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
0, 0, null, DataRowVersion.Current, bytBLOBData);
cmd.Parameters.Add(prm);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ MessageBox.Show(""+ex); }
}
private void button3_Click(object sender, EventArgs e)
{
try
{
//Getting The Image From The System
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
pictureBox2.Image = new Bitmap(open.FileName);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
2.在图片框中显示之前,有办法检查图像的大小。提前谢谢
答案 0 :(得分:1)
关于我看到你将文件保存为bmp格式的东西,并且最初该图片以jpeg或tiff格式存在,所以记录正确插入但图片指的是bmp格式并且它不存在。 我想你可以这样做。
如果您想知道如何创建缩略图(将文件保存为JPG格式,那么最受欢迎。