|
Hi,
Been checking around the net for the above subject and found a lot of solutions but seems not able to work for me.
This is my situation, I am using a textbox with type='file' to get the image from local. Then when user clicks a button, it suppose to convert the picture user chose into binary data and save it into the MSSQL database which in the column declared as binary(5000). When the user load the page again, I want the system to get the binary data from the database, covert it back to the original format, and place it in the tag.
Here is the code I'm using but I suspect something is just not right.
byte[] imagecontent = null;
if (fudLogo.Value != "")
{
string strfile = System.IO.Path.GetFileName(fudLogo.PostedFile.FileName);
string strexten = System.IO.Path.GetExtension(fudLogo.PostedFile.FileName);
if (strexten.Equals(".jpg") || strexten.Equals(".JPG") || strexten.Equals(".gif") || strexten.Equals(".GIF") || strfile.Equals(""))
{
System.IO.Stream stream;
Int64 imagesize;
int imgstatus;
imagesize = fudLogo.PostedFile.ContentLength;
stream = fudLogo.PostedFile.InputStream;
imagecontent = new byte[stream.Length];
}
}
else
{
imagecontent = this.strCpyLogo;
}
if (this.staff.UpdateCompany(this.txtCompanyName.Text, imagecontent, this.txtAddress1.Text, this.txtAddress2.Text, this.txtAddress3.Text,
this.txtPostCode.Text, this.txtState.Text, this.txtCountry.Text, Application["compid"].ToString()) == true)
{
Response.Redirect("E09-WorkingDayM.aspx?compid=" + Application["compid"].ToString() + "&empid=" + this.strEmpId + "&resetting=1");
}
else
{
this.lblErrMsg.Text = "Could not update company info at this moment.";
}
I tried to view the raw binary data just to check whether it is right by using below code
string aa = "";
for (int i = 0; i < imagecontent.Length - 1; i++)
{
aa += imagecontent[i].ToString();
}
this.Label11.Text = aa;
What I got is
000000000000000000000000000000000000000000000000000000000............
Which I feel it is just not right.
This is my first time dealing with binary data, hope to get some expert advice from here. Thanks.
|
|
|
|
|
J Liang wrote: imagecontent = new byte[stream.Length];
This is the problem. You are initializing a new byte array and not copying stream contents to this array.
if (strexten.Equals(".jpg") || strexten.Equals(".JPG") || strexten.Equals(".gif") || strexten.Equals(".GIF") || strfile.Equals(""))
{
System.IO.Stream stream;
Int64 imagesize;
int imgstatus;
imagesize = fudLogo.PostedFile.ContentLength;
stream = fudLogo.PostedFile.InputStream;
imagecontent = new byte[stream.Length];
stream.Read(imagecontent,0,imagecontent.Length);
}
|
|
|
|
|
Thanks, it works now.
I got this
25521625522401674707370011107207200255225310069120105102007373420800070151201000098000161209000108000
491202700011800050120....
Is this what I suppose to get? The numbers do turn different as I upload different pictures.
Now I know there is a lot of solutions out there to turn the above binary back to an image file but I just could not find one working, is there any code which any of you are using that is working? Can shade some light for me? Thanks.
|
|
|
|
|
J Liang wrote: Is this what I suppose to get? The numbers do turn different as I upload different pictures.
It depends on the file you are uploading. This will change for image to image.
J Liang wrote: out there to turn the above binary back to an image file
using (MemoryStream stream = new MemoryStream(b))
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
{
}
}
Hope this helps
|
|
|
|
|
I'm not really understand this line
Do you mean to assign System.Drawing.Image image into my
<asp:image id="imgLogo" runat="server" height="120px" visible="True" width="120px" />
This is what I did from your code given
using (MemoryStream stream = new MemoryStream(strCpyLogo))
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
{
}
}
Where strCpyLogo is in type byte which I retrieve from my database. In the database, strCpyLogo shows <binary data=""> which i assumed it had already saved into the database.
I'd tried this.imgLogo but could not find any command that seems logic to me to assign System.Drawing.Image image to it.
|
|
|
|
|
To set that image to a image control, create a seperate page say "DisplayImage.aspx". As I said in the last post, take Image instance and call image.Save(Response.OutputStream,ImageFormat.Jpeg) which save the image to output stream. The image format varies depending on your image extension. Also don't forget to set the response content type like Response.ContentType = "image/jpeg" (Only for jpg).
In the image control, set image url as this page(DisplayImage.aspx), you are done.
|
|
|
|
|
I got a error message when I run the code
Exception Details: System.ArgumentException: Parameter is not valid.
on this line
using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
I am doing this in my code
byte[] strCpyLogo;
Response.ContentType = "image/jpeg";
using (MemoryStream stream = new MemoryStream(strCpyLogo))
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
{
}
}
Where strCpyLogo was a binary data from the database
|
|
|
|
|
J Liang wrote: System.ArgumentException: Parameter is not valid.
Image class throws really weird errors. In the code shown here, you have not filled the byte array.
|
|
|
|
|
After some checking, I tried to do a select statement in Mssql and found out that there are values in the image column of my table (a bunch of alpha numeric)
I'd tried checking the strCpyLogo.Length and it only show me 26.
Now I really lost, not really sure where should I go now.
The piece of code you show me earlier
using (MemoryStream stream = new MemoryStream(strCpyLogo))
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
{
}
}
Is this suppose to help me create a physical jpg file and allow my tag to point to that jpg file? I saw a few example which is uses similar approach as you shown me here.
|
|
|
|
|
I think i realized there is a place where could cause all these.
I uses a stored procedure to get the binary data out but I'd declare in my coding as byte[]. So it gives me a problem when I do
SqlParameter objParam2;
objParam2 = myCommand.Parameters.Add("@cpyLogo", SqlDbType.Binary, 5000);
objParam2.Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
if (objParam2.Value == DBNull.Value)
{
cpyLogo = null;
}
else
{
cpyLogo = Convert.ToByte(objParam2.Value); <--Note it is not converting to byte[]
}
So I found in the internet where they uses this function to convert to byte array
public static byte[] ConvertStringToByteArray(string stringToConvert)
{
return (new UnicodeEncoding()).GetBytes(stringToConvert);
}
And I changed my code to
if (objParam2.Value == DBNull.Value)
{
cpyLogo = null;
}
else
{
cpyLogo = ConvertStringToByteArray(objParam2.Value.ToString());
}
Later I realized I'd read some where that I should not threat binary data as string (objParam2.Value.ToString()), could this be the problem? Or there is another way to change my objParam2.Value to byte array?
I think now what I need to do is to find out how to convert binary to byte array first.
modified on Thursday, June 12, 2008 5:21 AM
|
|
|
|
|
Hello everyone,
I have a detailsview grid and AccessDataSource as following:
<asp:accessdatasource id="UsersAcessDS" runat="server" datafile="~/DataBase/MoviesProject.mdb" selectcommand="SELECT * FROM Users ORDER BY ID">
UpdateCommand="UPDATE [Users] SET [Name] = ?, [LastName] = ?, [EmailAddress] = ?, [NickName] = ?, [IdentityCard] = ?, [Password] = ?, [IsAdmin] = ?, [LoggedIn] = ?, [CreditID] = ?, [ModifiedDate] = NOW()
WHERE ([ID] = ?)"
InsertCommand="INSERT INTO Users(Name, LastName, EmailAddress, NickName, IdentityCard, [Password], IsAdmin, LoggedIn, CreditID, CreatedDate, ModifiedDate)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())"
DeleteCommand="DELETE FROM Users WHERE ([ID] = ?)">
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="EmailAddress" Type="String" />
<asp:Parameter Name="NickName" Type="String" />
<asp:Parameter Name="IdentityCard" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="IsAdmin" Type="Boolean" />
<asp:Parameter Name="LoggedIn" Type="Boolean" />
<asp:Parameter Name="CreditID" Type="Int32" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="EmailAddress" Type="String" />
<asp:Parameter Name="NickName" Type="String" />
<asp:Parameter Name="IdentityCard" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="IsAdmin" Type="Boolean" />
<asp:Parameter Name="LoggedIn" Type="Boolean" />
<asp:Parameter Name="CreditID" Type="Int32" />
</InsertParameters>
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
</asp:AccessDataSource>
When I do UsersAcessDS.Insert();
I get the following error message
And I really dont understand way because I do fill this filed....
Server Error in '/MoviesProjectSite' Application.
--------------------------------------------------------------------------------
The field 'Users.Name' cannot contain a Null value because the Required property for this field is set to True. Enter a value in this field.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: The field 'Users.Name' cannot contain a Null value because the Required property for this field is set to True. Enter a value in this field.
Source Error:
Line 79: protected void UsersDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
Line 80: {
Line 81: this.UsersAcessDS.Insert();
Line 82: DataBind();
Line 83: }
Source File: d:\C#\My Projects\MoviesProjectAspNet\MoviesProject\MoviesProjectSite\AdministrativeZone.aspx.cs Line: 81
Stack Trace:
[OleDbException (0x80004005): The field 'Users.Name' cannot contain a Null value because the Required property for this field is set to True. Enter a value in this field.]
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +65
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +181
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +307
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +77
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +188
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +112
System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +496
System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +549
System.Web.UI.WebControls.SqlDataSourceView.Insert(IDictionary values) +29
System.Web.UI.WebControls.SqlDataSource.Insert() +38
AdministrativeZone.UsersDetailsView_ItemInserting(Object sender, DetailsViewInsertEventArgs e) in d:\C#\My Projects\MoviesProjectAspNet\MoviesProject\MoviesProjectSite\AdministrativeZone.aspx.cs:81
System.Web.UI.WebControls.DetailsView.OnItemInserting(DetailsViewInsertEventArgs e) +131
System.Web.UI.WebControls.DetailsView.HandleInsert(String commandArg, Boolean causesValidation) +512
System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +725
System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e) +163
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +56
System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e) +118
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +56
System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +106
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +203
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +72
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3824
Thank you
|
|
|
|
|
Those data sources are retarded. I'm sure this can be fixed, but I flat out would not use them anyhow.
I presume your name is sometimes NULL and it should not be ?
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
Can anyone please tell me what shpuld I do?
I know that I get Null but I can't understand why?
modified on Thursday, June 12, 2008 1:57 PM
|
|
|
|
|
I am creating a survey in asp.net to rate 46 departments from 1-5 on there quality, interpersonal skills, and timelines. Then store the data into a sql database. I am trying to figure out how I want to create the tables and I was wondering if anyone can provide any ideas. Should I create a table for each department with columns: quality, interpersonal, and timelines? If I do it this way I will have to create 46 tables which is alot. Or, should I just create one table and create columns for department, quality, interpersonal, and timelines.
Any feedback would help.
Thanks!
jds1207
|
|
|
|
|
Sounds like a SQL question.
I'd create one table if the columns are all the same, just add a department name column. Then you can add/remove depts easily.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
|
hw to get checked rows of gridview which is bubbled with checkboxes in c#.net.
with regards
n.priya
priya
|
|
|
|
|
Four basic questions in a row, two being the same one. Perhaps you need to buy a book ? Or at least read/search the articles on CP ?
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
plz find me a sol to add pop up calender in gridview using c#
with regards
n.priya
priya
|
|
|
|
|
You mean to say, you wants a link in grid view and when user clicked on that link then open a popup clender ?
Parwej Ahamad
R & D with IIS 5.0/6.0
|
|
|
|
|
plz find me a solution to add pop up calender in gridview.
with regards
n.priya
priya
|
|
|
|
|
use a javascript calendar.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
how to set fontsize,color in .cs file(i know to do in .aspx page hw to do in codebehind.can anyone help me
with regards
priya
priya
|
|
|
|
|
You have been told how to do this already.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
I have a Button(Select All Button) and a GridView a with a checkbox with columns EmployeeID, FirstName. GridView has paging enabled. After page loads, first, I check one check box from GridView's page one. I check another check box in page two. I hit Select All button. I need to get the employeeID values of those checked boxes from both pages.
With Below code, the problem is I, only get the employeeID from first Page not from second page?
How do I get the selected values from second page?
protected void SelectAll_Click(object sender, EventArgs e)<br />
{<br />
int employeeID;<br />
<br />
for (int i = 0; i < GridView1.Rows.Count; i++)<br />
{<br />
CheckBox chk = GridView1.Rows[i].FindControl("chkSelect") as CheckBox<br />
<br />
if (chk.Checked == true)<br />
{<br />
employeeID = Convert.ToInt32(GridView1.Rows[i].Cells[1].Text); <br />
}<br />
}<br />
<br />
}
CSharp Guy
|
|
|
|
|