insert/update/delete image from sql data with asp.net - c#

I want to insert/delete,update image in sql database using asp.net. My code of inserting is:
Stream strm = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(strm);
byte[] img = br.ReadBytes(Convert.ToInt32(strm.Length));
imgDetail.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(img, 0, img.Length);
imgDetail.Visible = true;
try
{
cmd = new SqlCommand("insert into Persons (id,Name,Surname,Address,Phone,Picture,Department) values (#id,#Name,#Surname,#Address,#Phone,#img,#Department)",con);
cmd.Parameters.AddWithValue("id", txtId.Text);
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Surname", txtSurname.Text);
cmd.Parameters.AddWithValue("Address", txtAddress.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("img", img);
cmd.Parameters.AddWithValue("Department", Department.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I think something went wrong with added image, maybe i do this wrong .Now when i click on some record in my gridview, all data of the record displays in the textboxes, but i cant do display image in imagebox. how can i do this?
this is part of displaing data in textboxes:
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex == GridView1.SelectedIndex)
{
GridViewRow row1 = GridView1.SelectedRow;
txtId.Text = row.Cells[0].Text;
txtName.Text = row.Cells[1].Text;
txtSurname.Text = row.Cells[2].Text;
txtAddress.Text = row.Cells[3].Text;
txtPhone.Text = row.Cells[4].Text;
Department.Text = row.Cells[5].Text;
Image.??????

The "Image" control is a just a wrapper around the standard <img> HTML-tag. So obviously it does not have any binary property, that you can set to a byte-array.
But you go with a "data" uri.
Here's an idea for you:
Image.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])imagedata);

Related

Loading Image through label

I am trying to load an image through label using this code
private void getData()
{
SqlConnection conn = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
conn.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT empName,empLname,empMi,empImage
FROM employees
WHERE empName = '"+ ddlAvail.SelectedItem.Value.ToString() +"'", conn);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblName.Text = rdr.GetValue(0).ToString();
lblLname.Text = rdr.GetValue(1).ToString();
lblMi.Text = rdr.GetValue(2).ToString();
lblImage.Text = "<img runat='server' src='" + rdr.GetValue(3).ToString() + "'></img>";
}
}
conn.Close();
}
every time I select a dropdownlist value it generates me set of sql data.My only problem is the image.Cause it wont load any image at all.The filepath on my visual studio and image name is correct.
This is an example of my image
../Images/Profile/logo.jpg
I save the images filepath on my database.
Your code looks fine
Make sure the file path your are retrieving from the database exists and the path isn't returning any unwanted characters.
That is:
rdr.GetValue(3).ToString() //should return the right path (string)
It should be fine. Hope this helped
It won't ever show the image because all that your code is doing is setting the text on the label.
If you want to display the image try this , or this.

ASP.NET - How to display image in browser without saving image in temp?

I have a question- How to display image in browser without saving image in Temp folder? Is it even possible? My code have to reading images from database and displaying images in website. I actually try with converting data from database and I don't know what I want to do.
I try also with "imageHandlers", "FileStream", "Base64StringToBitmap" and nothing still works...
Please write example code or modify my code.
private void LoadImages()
{
ImageButton imageButton = new ImageButton();
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name, Data from tblFiles WHERE email = #CurrentUser";
cmd.Parameters.Add("#CurrentUser", SqlDbType.NVarChar);
cmd.Parameters["#CurrentUser"].Value = User.Identity.Name;
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
sdr.Read();
string fileName = sdr["Name"].ToString();
FileInfo fi = new FileInfo(fileName);
byte[] byte_image_string = ((byte[])sdr["Data"]);
string image_string = Convert.ToBase64String((byte[])sdr["Data"]) + fi.Name;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
Panel1.Controls.Add(imageButton);
System.Drawing.Image newImage;
if (byte_image_string != null)
{
using (MemoryStream stream = new MemoryStream(byte_image_string))
{
newImage = System.Drawing.Image.FromStream(stream);
//I want here display image to browser without saving
//string newPhoto = "";
//newImage.Save(newPhoto);
imageButton.ImageUrl = "data:image/jpg;base64," + newPhoto;
}
}
conn.Close();
}
}
}
}
}
My example image code from database:
0xFFD8FFE000104A46494600010100000100010000FFE1018C45786966000049492A0008000000020031010200070000002600000069870400010000002E00000000000000476F6F676C6500000500009007000400000030323230099007000B0000007000000086920700080100007B00000002A00400010000006F02000003A0
This is how I do it in one of my projects: Look src part
<p><a href='<%#"TheObject.aspx?O=" + Eval("ID") %>'><img runat="server" visible='<%#Eval("AttachmentID") != DBNull.Value %>' class="objPicture1" alt='<%Eval("Title") %>' width="340" height="260" src='<%#"~/Attachment.aspx?ID=" + Eval("AttachmentID")%>' /></a></p>
In Attachment.aspx you have this code:
protected void Page_Load(object sender, EventArgs e)
{
Guid objID = //take the ID of the object ?ID=""
DataRow attachmentRow = //fetch DataRow of the Attachment from Database
if (attachmentRow == null)
return;
Response.ContentType = attachmentRow["ContentType"].ToString();// value of this is image/gif or image/jpeg and etc.
Response.BinaryWrite((byte[])attachmentRow["Data"]); // Data is type image in my case
Response.End();
}
It looks like you are creating Base64String in wrong way. You are appending file name to it that should not work. just try following.
string image_string = Convert.ToBase64String((byte[])sdr["Data"]);
Assign directly it to ImageUrl. no need to use MemoryStream here.
imageButton.ImageUrl = "data:image/jpg;base64," + image_string;

Not getting image in Image Control by Url in asp.net

Hello Friends i am storing an image via URL in database but when i retrieve it on Image Control of asp.net it doesn't show the image please help
Profile.aspx.cs
con.Open();
string str = "SELECT * FROM [aspdotnetpractice].[dbo].[Users] where Username ='" + lblHowdy.Text + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
Image1.ImageUrl = Server.MapPath(reader[8].ToString());
Label1.Text = reader[1].ToString();
Label2.Text = reader[2].ToString();
Label3.Text = reader[3].ToString();
Label4.Text = reader[6].ToString();
Label5.Text = reader[4].ToString();
reader.Close();
con.Close();
}
Make sure you save path value like "ImageFiles/test.jpg" or filename only like "test.jpg". Dont save to path field a complete local path like "c:\…\test.jpg". In imageurl you should use virtual path instead physical path.
The Server.MapPath returns a file name. On the other hand, Image.ResolveUrl expects a valid url.
You'd rather want something like
Image1.ImageUrl = Page.ResolveUrl("~/ImageFiles/") + fi.Name; // You just need to pass name or something similar.

asp.net display image(more than 2) from database using handler

Handler.ashx
public void ProcessRequest (HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(con);
connection.Open();
SqlCommand command = new SqlCommand("SELECT PhotoStoreTB.Data FROM PhotoStoreTB INNER JOIN UserTB ON UserTB.UserID = PhotoStoreTB.UserID WHERE PhotoStoreTB.UserID ='" + imageid + "'", connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
byte[] imagedata = (byte[])dr[0];
context.Response.ContentType = "image";
using (System.IO.MemoryStream str = new System.IO.MemoryStream(imagedata, true))
{
str.Write(imagedata, 0, imagedata.Length);
Byte[] bytes = str.ToArray();
context.Response.BinaryWrite(bytes);
}
connection.Close();
context.Response.End();
}
Exception Thrown from context.Response.End();
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
Aspx Code
<asp:Image ID="Image2" runat="server" ImageUrl='<%#"Handler.ashx?ImID="+ Eval("PUserID")%>'
Height="115px" Width="115px" CssClass="img-border"/>
I want to display multiple images in data list
Data List Bind
try
{
ld.Openconnection();
SqlCommand Cmd = new SqlCommand("PGetPropertyByCriteria", ld.con);
Cmd.Parameters.AddWithValue("#StartIndex", 1);
Cmd.Parameters.AddWithValue("#EndIndex", 10);
Cmd.Parameters.AddWithValue("#flag", "Get");
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter SqlAda = new SqlDataAdapter(Cmd);
DataSet DsStudentDetails = new DataSet();
SqlAda.Fill(DsStudentDetails);
if (DsStudentDetails.Tables.Count > 0 && DsStudentDetails.Tables[0].Rows.Count > 0)
{
TotalPage = (Int32.Parse(DsStudentDetails.Tables[0].Rows[0]["row"].ToString()) / PageSize) + ((Int32.Parse(DsStudentDetails.Tables[0].Rows[0]["row"].ToString()) % PageSize) > 0 ? 1 : 0);
CurrentRecord = DsStudentDetails.Tables[0].Rows.Count;
DataTable tDataTable = new DataTable("PagingTable");
tDataTable.Columns.Add(new DataColumn("LinkButtonVisible", typeof(bool)));
tDataTable.Columns.Add(new DataColumn("DisplayName", typeof(string)));
tDataTable.Columns.Add(new DataColumn("Value", typeof(string)));
tDataTable.Columns.Add(new DataColumn("LabelVisible", typeof(bool)));
dtlProduct.DataSource = DsStudentDetails.Tables[0];
dtlProduct.DataBind();
}
else
{
DLPAGING.DataSource = null;
DLPAGING.DataBind();
dtlProduct.DataSource = null;
dtlProduct.DataBind();
}
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
ld.Closeconnection();
}
Please Help me to display multiple images to datalist from database
Try using Response.Clear(); at the begining of ProcessRequest function.
Or
you can use ApplicationInstance.CompleteRequest instead of Response.Clear();
Change your response content type from
context.Response.ContentType = "image";
To
context.Response.ContentType = "image/jpeg(png)"; depends on type
and remove context.Response.End()
Just see the below sample code
byte[] image = imagefromDB();
context.Response.OutputStream.Write(image, 0, image.Length);
context.Response.ContentType ="image-mime-type";
I can't assure Response.CLear(); is a good idea though. Sometimes it gets glitchy. I know, I've tried.
try using jpg with the image response instead of jpeg. Sometimes it doesn't work either. jpg works all the time.
When you use a Handler, each instance of where the handler is called has its own Response object. Therefore you can bind the dynamic paths of the images from the server code.
using a GridView and binding the RowDataBound event you can do this quite easily.
protected void gvAlbumImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow aRow = ((DataRowView)e.Row.DataItem).Row;
//This is the Row from your Datasource (which is a datatable)
Image img = (Image)e.Row[e.Row.RowIndex].FindControl("imgControl");
//get the Image object at the row you are binding to.
//now simply set the source from the value in the DataRow
img.ImageUrl = string.format("~/ImageHandler.ashx?ImageID={0}",aRow.Field<int>("ImageID")
}
}

Displaying multiple image retrieving from database

My project allow admin to add medal for officer profile, currently I only able to insert the maximum of 5 medals. But my teacher ask me to let the admin insert as many medal as they want for the officer profile. I not sure how do I retrieve all the image that the admin inserted, I know how to insert image into database using varbinary. Do give me way for doing this. THANKS!
Code Below is how I do for inserting at maximum of 5 medals:
Code for uploading:
System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, 1024, 768);
}
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
string sqlImage = "Insert into OfficerMedal(policeid, image) values ('" + Session["policeid"] + "', #Data)";
SqlCommand cmdImage = new SqlCommand(sqlImage);
cmdImage.Parameters.AddWithValue("#Data", results);
InsertUpdateData(cmdImage);
I retrieve image using aspx page
protected void Page_Load(object sender, EventArgs e)
{
string strQuery = "select image from OfficerMedal where policeid='" + Session["policeid"] + "'";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
// check if you have any rows at all
// no rows -> no data to convert!
if (dt.Rows.Count <= 0)
return;
// check if your row #0 even contains data -> if not, you can't do anything!
if (dt.Rows[0].IsNull("image"))
return;
Byte[] bytes = (Byte[])dt.Rows[0]["image"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Response.BinaryWrite(bytes);
Response.End();
}
To add on for this current method I retrieving image 1 by 1 from database. Instead of retrieving all image that belong to the officer.
The usual way to do this is with a HttpHandler rather than in your ASPX page itself. The handler is responsible for retrieving the image data from your database and outputting it as a graphic; it can then be used as the src for a regular <img> tag or the ImageUrl property for an <asp:image> control.
The easiest way to add a handler is to select Generic Handler in the Add New Item dialog:
In the code for the handler, ProcessRequest is the method that does the work e.g.
public void ProcessRequest(HttpContext context)
{
byte[] imageBytes;
// Get the id of the image we want to show
string imageId = context.Request.QueryString["ImageId"];
// Get the image bytes out of the database
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
// Pass in the image id we got from the querystring
SqlCommand cmd = new SqlCommand("SELECT image FROM PoliceMedal WHERE ImageId=" + imageId, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
reader.GetBytes(0, 0, imageBytes, 0, int.MaxValue);
}
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite(imageBytes);
context.Response.End();
}
So we have our handler that will return the image data from the database, and we call this with a url like \ImageHandler.ashx?ImageId=1. This does require a change to your database in that you'll need to add a key to the PoliceMedal table - I suggest a SQL Server IDENTITY column.
It's not clear from your question how you're displaying the images on the ASPX page, so here I'll just show you how to add them into a PlaceHolder. So, we'll retrieve the set of image ids for an officer, construct an <asp:image> control for each of them and add the images to the PlaceHolder.
protected void Page_Load(object sender, EventArgs e)
{
using (
SqlConnection conn =
new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
// Query the table to get the list of image IDs for the current user
SqlCommand cmd = new SqlCommand("SELECT ImageId FROM PoliceMedal WHERE policeid = " + Session["policeid"], conn);
conn.Open();
SqlDataReader imageReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// For each image in the database
while (imageReader.Read())
{
// Create the new Image control
Image medalImage = new Image();
// Call the handler, passing the id of the image in the querystring
medalImage.ImageUrl = string.Format("ImageHandler.ashx?ImageId={0}",
imageReader.GetInt32(0));
// Add the image to the placeholder
MedalPlaceHolder.Controls.Add(medalImage);
}
}
}

Categories

Resources