Display an image in a Image container in WPF - c#

I am trying to display an image in an WPF Image container
string imageContent = ((DataRowView)dgQuestions.SelectedItem)["QuestionImage"].ToString();
if (imageContent.Length >= 5)
{
byte[] data = (byte[])((DataRowView)dgQuestions.SelectedItem)["QuestionImage"];
ImageSourceConverter imgConv = new ImageSourceConverter();
imageSource = (ImageSource)imgConv.ConvertFromString(data.ToString());
}
The last line of the above code generates the following error
object reference not set to an instance of an object
I'm not bothered with how the datagrid displays the image as the user will never see the it.
This is how I am filling the grid:
SqlCommand cmd = new SqlCommand();
cmd.Connection = Con;
cmd.CommandText = "getQuizQuestions";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#quizid", SqlDbType.Int)).Value = quizId;
cmd.ExecuteNonQuery();
SqlDataAdapter daSubject = new SqlDataAdapter(cmd);
DataSet dsSubject = new DataSet();
daSubject.Fill(dsSubject, "QuizSubject");
dgQuestions.ItemsSource = dsSubject.Tables[0].DefaultView;

Set a breakpoint and validate data isn't null. Also, why don't you set the image source as the byte[] instead of using a ToString():
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
public Byte[] BufferFromImage(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}

Related

C# SQL to get a picture from the database

I have this code:
private void LoginBTN_Click(object sender, EventArgs e)
{
var loguser = AutorizeLoginBox.Text;
var passuser = AutorizePasswordBox.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
string querystring = $"select ID, USERLOGIN, USERPASSWORD, USERAVATAR from USERTESTDB where USERLOGIN='{loguser}' and USERPASSWORD='{passuser}'";
SqlCommand command = new SqlCommand(querystring, sqldb.getConnection());
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count == 1)
{
byte[] arr;
Image imgcur;
ImageConverter converter = new ImageConverter();
arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString(), );
MemoryStream ms = new MemoryStream(arr);
Image i = Image.FromStream(ms);
Program.programpg.avatarbox.Image = i;
}
}
How to upload the image assigned to this user in the database after login. //symbolforfixdetails//symbolforfixdetails//symbolforfixdetails//symbolforfixdetails
This is how the database looks like:
Error is on this line:
arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString() );
Error:
System.NotSupportedException: "ImageConverter cannot convert from System.String."
Try the following code to set the PictureBox.Image from image stored in SQL Server. The code is tested and works as intended.
Part 1: retrieve image from database and set it to PictureBox.Image:
DataTable table = new DataTable();
byte[] arr=null;
using (SqlConnection cn = new SqlConnection(cs))
{
cn.Open();
using (SqlDataAdapter ad = new SqlDataAdapter("select top 1 USERAVATAR from USERTESTDB", cn)) // Replace SQL query with yours
{
ad.Fill(table);
}
}
arr = (byte[])table.Rows[0][0];
// Replace it with [0][3] according to your posted query
System.Drawing.Bitmap bitmap = null;
ImageConverter converter = new ImageConverter();
System.Drawing.Image img =
(System.Drawing.Image)converter.ConvertFrom(arr);
bitmap = (System.Drawing.Bitmap)img;
pictureBox1.Image = bitmap;
Part 2: store image in database:
openFileDialog1.ShowDialog();
string path = openFileDialog1.FileName;
byte[] img = null;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
using (SqlConnection cn = new SqlConnection(cs))
{
cn.Open();
using (SqlCommand cm = new SqlCommand("insert into USERTESTDB Values (#img)",cn))
{
cm.Parameters.Add(new SqlParameter("#img", img));
cm.ExecuteNonQuery();
}
}
You didn't asked about Part2, but I included it to ensure that the image is stored correctly (as binary data) in the database.
You have two problems with your line of code
arr = byte[])converter.ConvertFromString(table.Rows[0].ToString());
You used table.Rows[0] (which returns the entire row) instead of table.Rows[0][x] where x = the index of image column.
You can't convert String to Image in this way, check question 3594239 for more details.
Please Set your Db Column Data type to Varbinary(Max) which you store image's bytes.
Then read this binary to a MemoryStream() as you did but without convert.
If its a winforms project there should be an overload in PictureBox's DataSource (or whatever its name. if i don't remember wrong its name is Image or BackgroundImage) as it accepts directly byte array.
If Winforms, Either you can pass as byte array or Convert to an Image object and set it to datasource.
But if its a web project, then either you could set it as a base64 data/png string or Image object.
Hope this helps.

How to get back picture from sql database?How to enlarge the size of binary column? [duplicate]

This question already has answers here:
Retrieve Images from sql server database
(4 answers)
Closed 6 years ago.
I have a name & picutre saved in a database with this method:
Image img = Image.FromFile(imgLoc);
MemoryStream tmpStream = new MemoryStream();
img.Save(tmpStream, System.Drawing.Imaging.ImageFormat.Png);
tmpStream.Seek(0, SeekOrigin.Begin);
byte[] imgBytes = new byte[4000];
tmpStream.Read(imgBytes, 0, 4000);
string sqlquery = ("INSERT INTO Firma (Name, Logo)" +
"Values(#name, #logo)");
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#logo", imgBytes);
cmd.ExecuteNonQuery();
MessageBox.Show("Erfolgreich hinzugefĆ¼gt!");
cn.Close();
this.Close();
Now I want to have the picture back and displayed in a picturebox.
My code does not work.
cn.Open();
comm = "SELECT Logo From Firma WHERE FirmenNr LIKE #Firma ";
cmd = new SqlCeCommand(comm, cn);
cmd.Parameters.Add("#Firma", SqlDbType.NVarChar, 100).Value = FirmenNr.ToString();
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(cmd);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
MemoryStream mem = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(mem);
}
cn.Close();
the picture is safed as binary with the length 4000.
EDIT: how can I make this larger? visual studio does not allow me to set it to values above 4030.
You have a mistake here:
data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
You're accessing the column pic, but you query for Logo
Method to Put File into database from Drive:
public static void databaseFilePut(string imgLoc) {
byte[] file;
using (var stream = new FileStream(imgLoc, FileMode.Open, FileAccess.Read)) {
using (var reader = new BinaryReader(stream)) {
file = reader.ReadBytes((int) stream.Length);
}
}
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand("INSERT INTO Firma(Name, Logo)Values(#File)", varConnection)) {
sqlWrite.Parameters.Add("#File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
}
This method is to Get File from Database and Show In Picture Tool:
public static void databaseFileRead(string varID, string varPathToNewLocation) {
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(#"SELECT [Logo] FROM [dbo].[Firma] WHERE [RaportID] = #varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("#varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
pictureBox1.Image = Image.FromStream(memoryStream);
}

ASP.NET: image quality decrease when using ashx to preview

My webpage allow user upload images, and save images to SQL Server, and display images back to the user. The following code is how I save images:
FileUpload img = (FileUpload)fileUploadLocationPic;
Byte[] imgByte = null;
string strFileExtension = Path.GetExtension(img.PostedFile.FileName.ToString());
// Create a FILE
HttpPostedFile File = fileUploadLocationPic.PostedFile;
// Create byte array
imgByte = new Byte[File.ContentLength];
// force control to load data
File.InputStream.Read(imgByte, 0, File.ContentLength);
strQuery = "INSERT INTO [Table](Image) VALUES(#LocImage)";
SqlParameter ParamLocImage = new SqlParameter();
ParamLocImage.ParameterName = "#LocImage";
ParamLocImage.Value = imgByte;
cmd.Parameters.Add(ParamLocImage);
Here is how I retrieve from database using ashx:
public Stream ShowEmpImage(string PLID){
string connectionString = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
//string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sql = "SELECT [Image] FROM [Table] WHERE [ID] = #PLID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#PLID", PLID);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public void ProcessRequest(HttpContext context){
string PLID = "";
PLID = (context.Request.QueryString["PLID"]);
context.Response.ContentType = "image/jpg";
Stream strm;
strm = ShowEmpImage(PLID);
int count = 2048;
byte[] buffer = new byte[count];
int byteSeq = 0;
try
{
byteSeq = strm.Read(buffer, 0, count);
}
catch
{
}
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, count);
}
}
At last, I use
<asp:Image ID="imageChargingLocation" runat="server" />
imageChargingLocation.ImageUrl = "~/Editor/ShowImage.ashx?PLID=" + strPLID;
to retrieve image.
But I got image quality decrease here.
What should I do? (images are jpg. Same problem when tried png.)

How to retrieve image from Oracle database using C# web application?

I want to retrieve an image from an Oracle database to an Image control in asp.net. I tried but it's not working.
This is the code used for inserting image into database:
protected void btnUpload_Click(object sender, EventArgs e)
{
int imgLength = 0;
string imgContentType = null;
string imgFileName = null;
Stream imgStream = FileUpload.PostedFile.InputStream;
imgLength = FileUpload.PostedFile.ContentLength;
imgContentType = FileUpload.PostedFile.ContentType;
imgFileName = FileUpload.PostedFile.FileName;
if (imgContentType == "image/jpeg" || imgContentType == "image/gif" ||
imgContentType == "image/pjpeg"
|| imgContentType == "image/bmp")
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
FileStream fls;
fls = new FileStream(#imgFileName, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
string query = "insert into image(id,name,photo) values(1,'" + imgFileName + "'," + " :BlobParameter )";
// Establish a new OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.CommandText = query;
cmd.Connection = DbConnection;
cmd.CommandType = CommandType.Text;
System.Data.OracleClient.OracleParameter paramImage = new System.Data.OracleClient.OracleParameter("image",
Oracle.DataAccess.Client.OracleDbType.Blob);
paramImage.ParameterName = "BlobParameter";
paramImage.Value = blob;
paramImage.Direction = ParameterDirection.Input;
cmd.Parameters.Add(paramImage);
cmd.ExecuteNonQuery();
}
Table:
Id Name Photo
1 C:\\user\pictures\animal.jpeg (BLOB)
Below is the code used to retrieve the image into an image control but this code is not working.
For the past two days I've been struggling with this
void GetImagesFromDatabase()
{
try
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
OracleCommand cmd = new OracleCommand("Select name,photo from Image", DbConnection);
OracleDataReader oda = cmd.ExecuteReader();
while (oda.Read())
{
string path = oda[0].ToString();
img.ImageUrl = path;
if(oda.GetValue(1).ToString() !=""){
FileStream fls;
fls = new FileStream(#path, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
MemoryStream memStream = new MemoryStream(blob);
img.ImageUrl = oda[2].ToString();
}
}
}
catch (Exception ex)
{
}
}
Any ideas? Thanks in advance
maybe this code can help you:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

Loading PictureBox Image From Database

i'm trying to load images from database to a PictureBox. I use these following codes in order to load them to my picture. I've written some code but don't know what I should do for continuing.
Any help will be appreciated.
private void button1_Click(object sender, EventArgs e)
{
sql = new SqlConnection(#"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = sql;
cmd.CommandText = ("select Image from Entry where EntryID =#EntryID");
cmd.Parameters.AddWithValue("#EntryID", Convert.ToInt32(textBox1.Text));
}
Continue with something like this in the button1_Click:
// Your code first, here.
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;
if (count > 0)
{
var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"];
var stream = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(stream);
}
Assuming we have a simple database with a table called BLOBTest:
CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)
We could retrieve the image to code in the following way:
try
{
SqlConnection cn = new SqlConnection(strCn);
cn.Open();
//Retrieve BLOB from database into DataSet.
SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "BLOBTest");
int c = ds.Tables["BLOBTest"].Rows.Count;
if(c>0)
{ //BLOB is read into Byte array, then used to construct MemoryStream,
//then passed to PictureBox.
Byte[] byteBLOBData = new Byte[0];
byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image= Image.FromStream(stmBLOBData);
}
cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}
This code retrieves the rows from the BLOBTest table in the database into a DataSet, copies the most recently added image into a Byte array and then into a MemoryStream object, and then loads the MemoryStream into the Image property of the PictureBox control.
Full reference guide:
http://support.microsoft.com/kb/317701
private void btnShowImage_Click(object sender, EventArgs e)
{
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
Con = new OleDbConnection(#constr);
Con.Open();
Com = new OleDbCommand();
Com.Connection = Con;
Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id = " + val + " ";
OleDbDataReader reader = Com.ExecuteReader();
if (reader.Read())
{
byte[] picbyte = reader["Photo"] as byte[] ?? null;
if (picbyte != null)
{
MemoryStream mstream = new MemoryStream(picbyte);
pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
}
}
HERE IS A TOTAL ANOTHER WAY TO DO SO:
You can simply convert the Image to Text before saving it into DataBase and the then convert it back to the Image after reading it:
public string ImageToStringFucntion(Image img)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] imgBytes = ms.ToArray();
string FinalText = Convert.ToBase64String(imgBytes, 0 , imgBytes.Length);
return FinalText;
}
}
catch
{
return null;
}
}
Now you can Insert or Update your Database...
Now Let's consider you want it back:
public Image StringToImage_(string input_)
{
try
{
byte[] imgBytes = Convert.FromBase64String(input_);
using (MemoryStream ms = new MemoryStream(imgBytes))
{
Image img = Image.FromStream(ms, true);
return img;
}
}
catch (Exception ex)
{
return null;
}
}
Now you can do as follow:
// Considering you have already pulled your data
// from database and set it in a DataSet called 'ds',
// and you picture is on the field number [1] of your DataRow
pictureBox1.Image = StringToImage_(ds.Table[0].Rows[0][1].ToString());

Categories

Resources