convert long binary data in database access to image using c# - c#

here is my code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from StudentInformation where [StudentID] = " + txtStudentID.Text + "";
command.CommandText = query;
OleDbDataReader read = command.ExecuteReader();
while (read.Read())
{
txtStudentID.Text = (read["StudentID"].ToString());
txtFirstname.Text = (read["Firstname"].ToString());
txtLastname.Text = (read["Lastname"].ToString());
byte[] imgbyte = (byte[])read["Image"]; //when i add this a got error with this code
MemoryStream ms = new MemoryStream(imgbyte);
StudentPicture.Image = Image.FromStream(ms);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
i get the error "Parameter is not valid"
someone can help me?
im so confused!
i tried all the codes what i searched but still Error :'(
sorry for my bad english
Your response will be greatly appreciated....

Try getting your byte array like this instead:
var binLength = read.Item[3].Length;
byte[] imgByte = new byte[binLength - 1];
var bytes = read.GetBytes(0,0,imgByte,0,imgByte.Length);
MemoryStream ms = new MemoryStream(imgByte);
StudentPicture.Image = Image.FromStream(ms);

Related

ORA-01460: unimplemented or unreasonable conversion requested-uploading files

Following is the code to upload file in party_images table.
protected void upload_Click(object sender, EventArgs e)
{
try
{
using (OracleConnection connection = new OracleConnection(conString))
{
connection.Open();
string filename = Path.GetFileName(FileUpload1.FileName);
string[] tokenize = filename.Split('.');
FileUpload1.SaveAs(Server.MapPath("~/files/") + descBox.Text + "." + tokenize[1]);
string sourceLoc = Server.MapPath("~/files/" + descBox.Text + "." + tokenize[1]);
FileStream fs = new FileStream(sourceLoc, FileMode.Open, FileAccess.Read);
byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
String block = " BEGIN " +
" INSERT INTO party_images(party_id, sr_no, descr, party_image) VALUES ('"+Session["userId"]+"',"+srNo.Text+",'"+descBox.Text+"."+tokenize[1]+"', :1); " +
" END; ";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.LongRaw);
param.Direction = ParameterDirection.Input;
param.Value = ImageData;
cmd.ExecuteNonQuery();
descBox.Text = "";
srNo.Text = "";
}
}
catch (Exception ex) {
ClientScript.RegisterStartupScript(this.GetType(), "unSuccessMessage", "window.onload = function(){ alert('"+ex.Message+"')};", true);
}
finally
{
populateGrid(loadFromDb());
}
}
table description is,
PARTY_ID is VARCHAR2(10)
SR_NO is NUMBER
DESCR is VARCHAR2(50)
PARTY_IMAGE is LONG RAW()
This function is uploading all the files i.e., images,.docx,.pdf,.sql but when I upload any .docx containing screen shots or pictures then the upper error appears.
I have tried the following links,
ORA-01460: unimplemented or unreasonable conversion requested
The requested format conversion is not supported.
ORA-01460: unimplemented or unreasonable conversion requested
But I haven't got any solution. How can I upload any type of file without having this error?
Why are you using LONG RAW to store binary objects? That's a datatype which has been deprecated for over twenty years.
If you define PARTY_IMAGE as a BLOB (or maybe BFILE) you will find it a lot easier to work with. Find out more.

SQL C#: Nothing gets returned from Result.Read()

When I use this code, I get null returned. But when I am trying to use the query by sql I get normal result.
Here is my code:
public byte[] GetInfo(UnturnedPlayer player , string vehiclename)
{
try
{
MySqlConnection connection = createConnection();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "select `info` from `" + GaragePlugin.Instance.Configuration.Instance.DatabaseTableName + "` where `player` = '#id' AND `vname` = '#name';";
connection.Open();
command.Parameters.AddWithValue("#id", player.CSteamID);
command.Parameters.AddWithValue("#name", vehiclename);
Console.WriteLine(command.CommandText.Replace("#id", player.CSteamID.ToString()).Replace("#name", vehiclename));
var result = command.ExecuteScalar();
if(result != null)
{
Console.WriteLine(result.ToString(), ConsoleColor.Blue);
byte[] bytearray = Convert.FromBase64String(result.ToString());
return bytearray;
}
connection.Close();
return new byte[500];
}
catch (Exception ex)
{
Logger.Log("Error with GetInfo: " + ex);
return new byte[500];
}
}
Byte[500] gets returned. Is there any way to fix it?
Thanks!
I believe your SQL statement should look like this:
command.CommandText = "select info from " + GaragePlugin.Instance.Configuration.Instance.DatabaseTableName + " where player = #id AND vname = #name;
and your parameters should be added to the collection like this:
command.Parameters.AddWithValue(#id, player.CSteamID);
command.Parameters.AddWithValue(#name, vehiclename);

Insert an image into Access database in C#

I have a Save button where I am able to Insert data into my Access database. One of that fields is "BrandImage" and there I will insert an image. The datatype from this field is Memo.
This is the code I already have:
try
{
con = new OleDbConnection(cs.DBConn);
con.Open();
string queryInserir = #"INSERT INTO tblPhone (BrandImage) VALUES (#BrandImage)";
cmd = new OleDbCommand(queryInsert);
cmd.Connection = con;
MemoryStream ms = new MemoryStream();
Bitmap bmpImage = new Bitmap(pcPhone.Image);
bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] data = ms.GetBuffer();
OleDbParameter parameter = new OleDbParameter("#BrandImage", OleDbType.WChar);
parameter.Value = data;
cmd.Parameters.Add(parameter);
cmd.ExecuteNonQuery();
MessageBox.Show("Info saved successfully", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Error\nDetalhes: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The pcPhone is a PictureBox
When I debug it and try to save it it will give me this error
Object reference not set to an instance of an object
on this line of code Bitmap bmpImage = new Bitmap(pcPhone.Image);
Could you help me with that?

Insert and read blob "pdf files" in oracle database with C#

I want to insert and read pdf blop to oracle with c#.I tried to do something below.I need insert oracle blop pdf file with C#.I am using this code
var fs = new FileStream(txtFileName.Text, FileMode.Open, FileAccess.Read);
var blobByte = new byte[fs.Length];
fs.Read(blobByte, 0, Convert.ToInt32(fs.Length));
fs.Close();
id=nextİd("tablename")//take ID_SEQ.NEXTVAL
var con = new racleConnection(System.Configuration.ConfigurationSettings.AppSettings["Orclsys"]);
var cmd = new OracleCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO tablename values(:id,:blopfile )";
OracleTransaction sqlTrans = con.BeginTransaction();
cmd.Transaction = sqlTrans;
try
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue(":id", Id);
var blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = ":blopfile ";
blobParameter.Value = blobByte;
cmd.Parameters.Add(blobParameter);
cmd.ExecuteNonQuery();
Result = true;
sqlTrans.Commit();
}
catch(Exception ex)
{
}
finally
{
con.Close();
con.Dispose();
sqlTrans.Dispose();
cmd.Dispose();
}
so I want read this file from db and i am starting code but I can not continue.
How can I continue after.could you help me.!!
try
{
orcl.Connect(DbUser.System);
orcl.CommandText = "SELECT blopfile FROM tablename WHERE id= :id";
orcl.ClearParameters();
orcl.AddParameter(":id", id);
orcl.ExecuteDataReader();
var lob = orcl.DataReader.GetOracleLob(0);
var pdffile= new Bitmap(lob);
//
//how can I continue code here....
//
}
catch(Exception ex)
{
}

Image Save and Retrieve in SQL Server in asp.net using c#

I am trying to save images in a SQL Server database.
I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.
I tried a lot but didn't find a solution.
Here is the code (convert bytes to Image)
if (fImage.HasFile)
{
if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
{
int filelenght = fImage.PostedFile.ContentLength;
byte[] imagebytes = new byte[filelenght];
fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into tbImage(Img) values(#img)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#img", imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Image saved to database");
}
}
Something like this will convert Byte[] to Image:
MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
byte[] img = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(img);
PictureBox1.Image = Image.FromStream(ms);
}
}
con.Close();
All you need to do is to store the byte content in a variable and then write it to the File system:
var imgBlob = ... // Load the image binary array from the database
File.WriteAllBytes("path/to/file.jpg", imgBlob);
you can create a controller action to handle retrieving the image
public FileResult DownloadImage(int Photo_Id)
{
byte[] fileBytes = "get bytes from db here";
string fileName = "file name here"
return File(fileBytes, "contentType of the image" , fileName);
}
Thanks for your valuable reply.
i solve this problem with this one.
give a look.
int id = Convert.ToInt32(drpImage.SelectedValue);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id+"", con);
con.Open();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
byte[] img = (byte[])dr["img"];
string base64string = Convert.ToBase64String(img, 0, img.Length);
lblImage.Text += "<img src='data:image/png;base64," + base64string + "' alt='No Image' width='200px' vspace='5px' hspace='5px' />";
}
}
con.Close();

Categories