using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace Images
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
using (SqlConnection connection2 = new SqlConnection("Data Source=.;Initial Catalog=users;Integrated Security=True"))
{
string q = "select photo from images where Id=@EMPID";
connection2.Open();
using (SqlCommand cmd = new SqlCommand(q, connection2))
{
cmd.Parameters.AddWithValue("@EMPID", textBox1.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
byte[] byteBLOBData =(byte[])reader["Photo"];
image2.BackgroundImage = ToImage(byteBLOBData);
}
}
}
}
}
/// <summary>
/// Gets the Image from a byte array
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static Image ToImage(byte[] Data)
{
if (Data == null)
{
return null;
}
Image img;
using (MemoryStream stream = new MemoryStream(Data))
{
using (Image temp =Image.FromStream(stream))
{
img = new Bitmap(temp);
}
}
return img;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog Open = new OpenFileDialog();
Open.Filter = "Image Files(*.jpeg; *.jpg; *.bmp)|*.jpeg; *.jpg; *.bmp";
if (Open.ShowDialog() == DialogResult.OK)
{
image2.BackgroundImage = new Bitmap(Open.FileName);
}
}
catch (Exception)
{
throw new ApplicationException("Image loading error...");
}
}
public byte[] ImageToByteArray(Image img)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
SqlConnection connection2 = new SqlConnection("Data Source=.;Initial Catalog=users;Integrated Security=True");
private void button2_Click(object sender, EventArgs e)
{
string q = "Insert into images (id,photo)select'" + textBox1.Text + "','" + image2.BackgroundImage + "' ";
connection2.Open();
SqlCommand cmd=new SqlCommand(q,connection2);
int Add=cmd.ExecuteNonQuery();
if(Add>0)
{
MessageBox.Show("Inserted.");
}
connection2.Close();
}
}
}
I am able to save the image but the image is no retrived the error is given by this line " using (Image temp =Image.FromStream(stream))" that is parameter is not valid.