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

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)

Related

How to insert PictureBox to Sql Server Database Varbinary(MAX) with C#?

I have a table that have a field as Varbinary(MAX) datatype and I want to insert image file from PictureBox into this column. So how can I convert and insert image to Varbinary in Sql Server. Thank for help me.
You should really show some code, what have you tried...
This is only a guess, but it should give you a clue how to insert picture into database:
//byte array that will hold image data
byte[] imageData = null;
using (var ms = new MemoryStream())
{
//here is image property of your pictureBox control saved into memory stream
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imageData = ms.ToArray();
}
//make sql connection
SqlConnection conn = new SqlConnection("your connection string goes here");
// command with parameter
SqlCommand cmd = new SqlCommand("insert into TableWithImages (imageData) values (#imageData);", conn);
//define param and pass byte array as value
cmd.Parameters.Add("#imageData", SqlDbType.VarBinary).Value = imageData;
//do insert
cmd.ExecuteNonQuery();

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;
}

populate list with images from database

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

GetBytes() can only be called on binary or GUID columns

I'm developing an app in C# with .NET and MySQL database. I need to be able to insert and retrieve images in and out of the database and I have a column named 'Image' of type LONGBLOB for that purpose. The insertion goes well but when I try to retrieve the blob the following error pops up:
GetBytes() can only be called on binary or GUID columns
I'm using the following code to select from the database:
Conn.Open();
string sql = #"SELECT `ID`, `Image`, `Note`"
+ " FROM `Item`"
+ " WHERE `ID` = ?ID";
MySqlCommand cmd = new MySqlCommand(sql, Conn);
cmd.Parameters.Add(new MySqlParameter("?ID", iD));
cmd.Prepare();
rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (rdr.Read())
{
this.ID= rdr.GetString("ID");
if (!rdr.IsDBNull(1))
{
long len = rdr.GetBytes(1, 0, null, 0, 0);
byte[] ImageBytes = new byte[len];
rdr.GetBytes(1, 0, ImageBytes, 0, (int)len);
MemoryStream ms = new MemoryStream(ImageBytes);
this.Image = Image.FromStream(ms);
}
this.Note = rdr.GetString("Note");
Despite changing the column type into binary and varbinary, I still got the same error.
Does anyone know what I'm doing wrong here?
TIA
Can't you just cast rdr["Image"] as byte[]?

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.

Categories