c# store a picture to database
I am not able to insert the picture in database.This is my sample code.I am able to select a image from my computer and display in picture box.Once i try to store the image displayed in picture box to database it says object reference not set to an instance of an object.
This is my sample code.
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)
开发者_JAVA技巧 {
throw new ApplicationException("Failed loading image");
}
}
2.There is any way check the size of the image before displaying it in picture box.Thank in advance
On thing i see that you save a file into bmp format and originally that picture exist with let say jpeg or tiff format, so the record is inserted rightly but the picture is refering to a type bmp format and it does not exist. I think you can do somehting like this.
- when you get the picture in any format you want, then create a thumbnail for this picture store it in a different folder*(like My Pictures\Thumbnails).*
- Get the extension of the picture,replace it with jpg during creation of Thumbnail.
- Store this in the database.
- Retrieve the thumbnails in the picture box. You want.
If you want to know how to create the Thumbnails (saving a file into JPG format then most welcome.
精彩评论