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?
Related
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);
I am trying to save and read back pdf files in a SQL Server CE local database. I was able to save them as binary data in an Image column, but I don't know how to read them back and open the pdf file (original format).
Table Schema
Here is how I stored the PDF files:
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string filePath = textBox1.Text.ToString();
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
cmd.Parameters.AddWithValue("#Data",bytes);
cmd.ExecuteNonQuery();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
con.Dispose();
}
Try this
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string strQuery = "select Data where Name = #Name and ContentType = #ContentType";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
SqlCeDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
byte[] pdf = (byte[])reader["Data"];
File.WriteAllBytes(filename, pdf);
}
}
}
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)
{
}
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();
SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read() == true)
{
lblHead.Text = sdr["HEADING"].ToString();
lblData.Text = sdr["COMMENT"].ToString();
}
conn.Close();
That is the code for normal data value retrieve from table now I want to get picture from SQL Server that is saved as Binary data that code mention in bottom. So I want to retrieve picture into an Image control of asp.net; please guide me.
if (FileUpload1.HasFile)
{
conn.Close();
String SqlQery;
SqlQery = "select max(CMTID) from FTAB";
SqlCommand cmdid = new SqlCommand(SqlQery, conn);
conn.Open();
MaxID = (int)(cmdid.ExecuteScalar()) + 1;
conn.Close();
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimg = FileUpload1.PostedFile;
myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (#imgid, #image, #comment, #datetm, #heading)", conn);
SqlParameter imgid = new SqlParameter("#imgid",SqlDbType.Int);
imgid.Value = MaxID;
cmd.Parameters.Add(imgid);
SqlParameter uploading = new SqlParameter("#image", SqlDbType.Image);
uploading.Value = img;
cmd.Parameters.Add(uploading);
SqlParameter cmtt = new SqlParameter("#comment", SqlDbType.NVarChar);
cmtt.Value = RadTextBox3.Text;
cmd.Parameters.Add(cmtt);
SqlParameter dttm = new SqlParameter("#datetm", SqlDbType.DateTime);
dttm.Value = DateTime.Now;
cmd.Parameters.Add(dttm);
SqlParameter hhding = new SqlParameter("#heading", SqlDbType.NVarChar);
hhding.Value = RadTextBox8.Text;
cmd.Parameters.Add(hhding);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lblHead.Text = "Image uploaded";
}
else
{
lblHead.Text = "No file selected";
}
Try this
SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
img.ImageUrl = filePath;
But I would say this isn't the best way to do it, you should save your uploaded images as files as in your website and save the path of that file in your database.
yogi's answer is correct in principle, but requires a web server directory "temp" and write access on an IIS directory.
You can also solve the problem using an image handler as explained in another SO question. Database retrieval is done in the same way, but the rendering happens from a stream, rather than a temp file.