populate list with images from database - c#

I want to retrieve the images from SQL table and save it in the list and show it in my listview. But I don't know how to do this. I need your help.
I am using SQL Server 2008, Visual Studio 2008, C# Window Application.
Here is my code:
cmd = new SqlCommand("Select ScanImage from ScanDocuments", con);
dr = cmd.ExecuteReader();
List<ImageList> lstitem = new List<ImageList>();
while (dr.Read())
{
ImageList _image = new ImageList();
byte[] data = (byte[])dr["ScanImage"];
MemoryStream ms = new MemoryStream(data);
Image bmp = new Bitmap(ms);
lstitem.Add(bmp);
}

Your code has several flaws - you need to use something like this instead:
// define connection string and select statement
// I used AdventureWorks 2012 database - change to match *YOUR* environment
string connectionString = "server=.;database=AdventureWorks2012;integrated security=SSPI;";
string query = "SELECT ThumbNailPhoto FROM Production.ProductPhoto";
// define a list of "Image" objects
List<Image> listOfImages = new List<Image>();
// using the SqlConnection and SqlCommand ....
using(SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
// open connection
conn.Open();
// execute SqlCommand to return a SqlDataReader
using (SqlDataReader rdr = selectCmd.ExecuteReader())
{
// iterate over the reader
while (rdr.Read())
{
// load the bytes from the database that represent your image
var imageBytes = (byte[]) rdr[0];
// put those bytes into a memory stream and "rewind" the memory stream
MemoryStream memStm = new MemoryStream(imageBytes);
memStm.Seek(0, SeekOrigin.Begin);
// create an "Image" from that memory stream
Image image = Image.FromStream(memStm);
// add image to list
listOfImages.Add(image);
}
}
conn.Close();
}
This works just fine for me - it loads the 101 ThumbNailPhoto from the AdventureWorks2012 database

Related

C# retrieving image in db. Get Error Parameter in not valid

I don't know what's wrong with my code in retrieving image in db. I insert image without using image path file cause the image provide by the cam.
Here's my code in inserting image in db
Image img = pictureBox1.Image;
MemoryStream memStream = new MemoryStream();
img.Save(memStream, ImageFormat.Bmp);
byte[] imageBt = memStream.ToArray();
query = "";
query += "INSERT INTO table(picture) VALUES ('" + imageBt + "')";
cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
con.close();
Here's my code in retrieving image in db
query = "";
query += "SELECT picture FROM table WHERE id = '1'";
cmd = new MySqlCommand(query, con);
con.Open();
MemoryStream ms = new MemoryStream();
byte[] image = (byte[])cmd.ExecuteScalar();
ms.Write(image, 0, image.Length);
con.Close();
Bitmap bmp = new Bitmap(ms)
pictureBox1.Image = bmp; //Still get the Error here parameter is not valid
Is there anywrong process in saving image in database. Btw my image type in db is Blob. I don't know why it doesn't work in retrieving image it always thrown error. Thanks
When reading, you haven't rewound the stream. If you Write, you must set ms.Position = 0; afterwards. Or simpler: create the stream from the data, then you don't need to:
byte[] image = ...
var ms = new MemoryStream(image);
When writing, you seem to have injected the data directly. That... almost certainly won't work - in fact, you're probably writing System.Byte[] to the command. Ideally, use a parameter:
query = "INSERT INTO table(picture) VALUES (#blob)";
cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("blob", imageBt);
cmd.ExecuteNonQuery();
(the exact syntax may change between RDBMS implementations)

Read Image from SQL Server VarBinary(Max)

I have a SQL Server Database. I have stored an image in there which is a varbinary(max). I inserted the image the following way :
string consString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection con = new SqlConnection(consString);
con.Open();
String filePath = fuImage.PostedFile.FileName;
String naam = Path.GetFileName(filePath);
String extension = Path.GetExtension(naam);
Stream stream = fuImage.PostedFile.InputStream;
BinaryReader br = new BinaryReader(stream);
Byte[] imgByte = br.ReadBytes((Int32)stream.Length);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spAddImage";
cmd.Parameters.AddWithValue("#FOTO", imgByte);
cmd.Parameters.AddWithValue("#ARTIEST", ddlArtiest.SelectedValue);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
The image now looks like this in the database :
It is stored as a varbinary.
http://puu.sh/ikF83/6a03b52520.png <--- database
Now I want to display my image on my asp.net page that I have inserted.
But I have no idea how I can achieve this.
You could use SqlDataReader to go over the results and get back what you need
var reader = cmd.ExecuteReader();
while (reader.Read())
{
byte[] myImage = (byte[])reader["MyImageColumn"];
}
This is from top of my head so make your adjustments as required. But it should give you the basic idea.
Furthermore, It's strongly recommended to use the using block as it ensures the object is disposed correctly.
So you could change your code to
using(var connection = new SqlConnection(connectionString))
{
//Your command
connection.Open();
//Datareader here
}//Object disposed here
Reference to SqlDataReader
Reference to using block
Extending the answer provided by Izzy, below is how we have implemented the same.
public HttpResponseMessage RenderImage(RenderRequest renderRequest, HttpRequestMessage request)
{
var httpResponse = new HttpResponseMessage();
try
{
var reader = cmd.ExecuteReader();
while (reader.Read())
{
byte[] imagebytes = (byte[])reader["MyImageColumn"];
}
return httpResponse = request.CreateResponse<byte[]>(HttpStatusCode.OK, imagebytes, new ImageMediaFormatter("image/png"));
}
catch ()
{
throw;
}
}

How to read VarBinary Data from the SqlServer ASP.Net

I have a binary data (Object of MyClass) in SqlServer field, But i am not able to retrieve the binary value and convert it into My Class Object.
I have used following code to write into the DB.
conn = getConnection();
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(sql);
SqlCommand sqlCmd = new SqlCommand(#"INSERT INTO PExercise(P_Enroll_No,P_Exercises,P_Date) VALUES (#VarEnroll,#VarBinary,#Date)", conn);
sqlCmd.Parameters.Add("#VarEnroll",System.Data.SqlDbType.NVarChar,Int32.MaxValue);
sqlCmd.Parameters["#VarEnroll"].Value = sql.getEnrollNo();
sqlCmd.Parameters.Add("#VarBinary", System.Data.SqlDbType.VarBinary, Int32.MaxValue);
sqlCmd.Parameters["#VarBinary"].Value = memStream.GetBuffer();
sqlCmd.Parameters.Add("#Date",System.Data.SqlDbType.NVarChar,Int32.MaxValue);
sqlCmd.Parameters["#Date"].Value = date;
int success = sqlCmd.ExecuteNonQuery();
closeConnection();
This code successfully writes my data into the table. I have used following code to read it from database.
please help me with the code.
conn = getConnection();
SqlCommand sqlCmd = new SqlCommand(#"Select P_Exercises from PExercise where P_Enroll_No='" + enrollNo + "' AND P_Date='"+date+"'", conn);
SqlDataReader dr = sqlCmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
byte[] bytes = new byte[1024];
long i = dr.GetBytes(0,0,bytes,0,1024*1024*8);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
mc = (List<ExerciseDetails>)bf.Deserialize(ms);
I have searched a lot but still have no luck.
Above code is giving me Exception "Invalid Read, No Data is Present".
I have also tried QueryManager to run the sql query. and its working fine there.
You could do something like the following where you do an ExecuteScaler as safe cast it as a byte array. By the way, make sure you wrap objects that implement IDisposable with using statements so they are closed and disposed properly.
using (var cn = _db.CreateConnection())
using (var cm = cn.CreateTextCommand(sql))
{
cm.AddInParam("name", DbType.String, name);
cn.Open();
var data = cm.ExecuteScalar() as byte[];
return data;
}

How to show preview of image using handler

I m using a handler to display images on my page from database
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["XYZ"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Image from EmployeeInfo where Emp_Id = #ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter("#ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
int height = Convert.ToInt32(context.Request.QueryString["Ht"]);
int width = Convert.ToInt32(context.Request.QueryString["Wt"]);
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
if (dReader.HasRows)
{
dReader.Read();
byte[] imagethumbnail = null;
try
{
imagethumbnail = MakeThumbnail((byte[])dReader["Image"], width, height);
}
catch
{
}
context.Response.BinaryWrite(imagethumbnail);
}
dReader.Close();
con.Close();
}
public static byte[] MakeThumbnail(byte[] myImage, int thumbWidth, int thumbHeight)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
using (Image thumbnail = Image.FromStream(new MemoryStream(myImage)).GetThumbnailImage(thumbWidth, thumbHeight, null, new IntPtr()))
{
thumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
This code works fine when displaying images from database.
Now What I want to do is to Show image preview using a different Handler.
Now if u look at the above code then you can see we have image data in byte[] form.
I m uploading a image and I m able to get the data in byte[] but this data of mine is on .cs page.
context.Response.BinaryWrite(imagethumbnail);
If I use this command converting data into bytes from page, it shows me the image on page nothing else.
Can you give me any idea how to show this data into image?
There is nothing much change in the datastream
This is what I want to use but how to get byte[] from .cs page to handler.
imagethumbnail = MakeThumbnail((byte[])dReader["Image"], width, height);
context.Response.BinaryWrite(imagethumbnail);
You can seperate your database image logic into a Generic Handler (ASHX) and then use the handler as your image's src e.g.
<img src="GetImage.ashx?id=1"/>
You'd need to create GetImage.ashx and handle your id's (or whatever your using) appropriately. Then you can do a simple write back to the page.
This will allow you to dynamically pull an image from the database while using it as a seperate element on your page.

How do I store a image BLOB in an access database after getting the name from openfiledialog?

I am developing a C# application that has an Access database. What I want to do is allow a user to select an image through an "openfiledialog." I then want to store the image in one of the table of the access database in a BLOB field. I have searched over the internet, but found nothing helpful. I hope you can help me.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// textBox1.Show(openFileDialog1.FileName.ToString());
// MessageBox.Show(openFileDialog1.FileName.ToString());
textBox1.Text = openFileDialog1.FileName.ToString();
String filename = openFileDialog1.FileName.ToString();
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Policias.accdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (#imagen)";
cmd.Parameters.AddWithValue("#imagen", buffer);
conn.Open();
cmd.ExecuteNonQuery();
}
}
else
{
MessageBox.Show("Porfavor selecciona una imagen");
}
}
but now how can I be sure that is stored in the access database?
Example:
string filename = "foo.txt"; // TODO: fetch from file dialog
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=foo.mdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO MyTable VALUES (#Name, #Data)";
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#Data", buffer);
cmd.ExecuteNonQuery();
}
What you will want to do is something similar to the following.
using (OpenFileDialog fileDialog = new OpenFileDialog){
if(fileDialog.ShowDialog == DialogResult.OK){
using (System.IO.FileInfo fileToSave = new System.IO.FileInfo(fileDialog.FilePath)){
MemoryStream ms = System.IO.FileStream(fileToSave.FullNae, IO.FileMode.Open);
//Here you can copy the ms over to a byte array to save into your blob in your database.
}
}
}
I would use File.ReeadAllBytes(file) and save the byte[] there in the DB.

Categories