I have done inserting image into database and the datatype is image, but when I want to retrieve it, it is very difficult and error will show Parameter is not valid.
public void RetrieveImage()
{
var con = new SqlConnection(Connection.CATAS_LOCAL());
string SQL = "Select Name,Image from dbo.[TestImage] where Name = 'Test1'";
var cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader Reader = cmd.ExecuteReader();
Reader.Read();
if (Reader.HasRows)
{
txtAddStaffNric.Text = Reader[0].ToString();
byte[] img = (byte[])(Reader[1]);
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms); ** error show at this line
}
con.Close();
}
Related
I am trying to upload an image to a mysql database. I upload the image on a asp.net page . But i am getting this error whenever i try to upload the image to the database.
System.FormatException: 'Input string was not in a correct format.'
on the line with this code
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
This is the complete code that i tried
protected void upload_files(object sender, EventArgs e)
{
if (FileUpload_UploadFile.HasFile)
{
HttpPostedFile img = FileUpload_UploadFile.PostedFile;
// IMPLEMENT YOUR CODE FOR SAVING THE FILE
Console.Write(img);
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
bytes = binaryReader.ReadBytes((int)stream.Length);
result = System.Text.Encoding.UTF8.GetString(bytes);
myLabel2.Text = "file has been uploaded";
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql_command = "Insert INTO Recognized_person1 (Name,Image,Department,Department_id) VALUES (#Name, #Image, #Department, #Department_id )";
conn.Open();
MySqlCommand MyCommand2 = new MySqlCommand(sql_command, conn);
MyCommand2.Parameters.AddWithValue("#Name", MySqlDbType.VarChar).Value = Name.Text;
MyCommand2.Parameters.AddWithValue("#Image", MySqlDbType.Blob).Value = bytes;
MyCommand2.Parameters.AddWithValue("#Department", MySqlDbType.VarChar).Value = Department.Text ;
MyCommand2.Parameters.AddWithValue("#Department_id", MySqlDbType.Int32).Value = Int32.Parse((Department_id1.Text));
//MyCommand2.ExecuteNonQuery();
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
conn.Close();
}
}
Any ideas on how to correct this error ?
I am trying to retrieve a picture stored in MS SQL Server database. The type of the column is image. My code is:
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream stream = new MemoryStream(image))
{
stream.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(stream);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am continuously getting ArgumentException as Parameter is not valid when I set the pictureBox1.Image property. I tried all the available solutions on the Internet but all in vain.
You are always using a 10000 byte array even if the image is smaller (or larger). Don't manually create the byte[], the DataReader can provide the entire byte array if you ask for it.
byte[] image = reader.GetFieldValue<byte[]>(0);
If you are not using .NET 4.5 you can just ask for the field and cast it manually.
byte[] image = (byte[])reader.GetValue(0);
However the fact that you are only using the first column from the first row you don't need a DataReader at all, just use ExecuteScalar() instead. (I also am cleaning up your code to use proper using statements and switched your ex.Message to ex.ToString() to provide more info in the error dialog).
try
{
using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using(SqlCommand cmd = new SqlCommand(string.Empty, con))
{
cmd.CommandText = "select Picture from Person";
con.Open();
byte[] image = (byte[])cmd.ExecuteScalar();
using (MemoryStream stream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Try this :
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(mStream);
}
I have the following method i am using to save an object into an SQL Server CE database. I am now stuck on how to get the record back out.
public void SaveRecord(LabRecord _labrecord)
{
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(_labrecord);
SqlCeCommand sqlCmd = new SqlCeCommand("INSERT INTO LabTransactions([TrasactionType], [CAM], [TransactionObject]) VALUES ('ResultTest', 1234, #Image)", conn);
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, Int32.MaxValue);
sqlCmd.Parameters["#Image"].Value = memStream.GetBuffer();
sqlCmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
Update
I am looking to make another class that returns a specific record.
public LabRecord getRecord(int transactionId)
{
LabRecord returnRecord = null;
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
//.... Get the record
}
finally
{
conn.Close();
}
return returnRecord;
}
I think the problem most likely lies in the fact that the size of the #Image parameter is being set to Int32.MaxValue
Set it instead to the length of the image byte stream:
byte[] imgBytes = memStream.GetBuffer();
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, imgBytes.Length);
sqlCmd.Parameters["#Image"].Value = imgBytes;
Here's an excerpt from this example (modified for your question) of how you might go about retrieving the image:
// Get the record
SqlCeCommand cmd = new SqlCeCommand("Select [TransactionObject] From LabTransactions Where [CAM] = 1234", conn);
conn.Open();
SqlCeDataReader sdr = cmd.ExecuteReader();
byte[] imgByteData = Convert.ToByte(sdr.Item("Picture"));
Bitmap bitmap = new Bitmap(new System.IO.MemoryStream(imgByteData));
I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}
I've a very basic form with just one picture box,one textfield and one button. I've created a table in Oracle to store a blob, I want to load that image into a picturebox in c# once the button is clicked. Here is what I've wrote so far.
My picturebox name = "picBoxXray". My textbox name = "txtXrayId". My button name = "btnGetXrayID". And My table name is "XRay".
private void btnGetXrayID_Click(object sender, EventArgs e)
{
if (txtXrayId.Text == "")
{
MessageBox.Show("XrayID be entered");
}
if (picBoxXray.Image != null)
{
picBoxXray.Image.Dispose();
}
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM XRay WHERE XrayID =" + txtXrayId.Text;
OracleCommand cmd = new OracleCommand(sql, connection);
OracleDataReader dr = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
// Obtain the image
//Need code
}
command.CommandText = sql;
command.ExecuteNonQuery();
connection.Close();
}
Any help would be greatly aprreciated,
Thanks
You have to create the image from a stream, for example:
public Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Then aassign the image to the picture box. the byteArray in is the blob you read from the db. of course the image have to be stored in a format known ( png/jpeg for instance )