C# SQL to get a picture from the database - c#

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.

Related

How to convert Blob value to Image

I have a BLOB value in a MySQL database.
I've read several tutorials, but I can not find a solution.
Any idea how I can read the image (blob value) and view it in an ASP.NET Image component?
All info i found is about array convert to image, but I have a Blob value
Did you try to read the image from db and put in a MemoryStream, then show it in an image component? Something like :
Byte[] byteBLOBData = new Byte[bufferSize];
byteBLOBData = "read image from database"
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pictureBox.Image = Image.FromStream(stmBLOBData);
Reference : https://bytes.com/topic/c-sharp/answers/965811-retrieve-blob-picture-mysql-database-c
Problem solved.
The exact problem was the query...
Code finished...
Image picture = new Image();
string queryImage = "SELECT image FROM news WHERE id = #id";
using (MySqlConnection con1 = new MySqlConnection(servidor))
{
MySqlCommand cmd1 = new MySqlCommand(queryImage, con1);
cmd1.Parameters.AddWithValue("#id", rd[0]);
con1.Open();
byte[] bytesImage = (byte[])cmd1.ExecuteScalar();
picture.ImageUrl = "data:image;base64," + Convert.ToBase64String(bytesImage);
}

Issue while inserting images to the mysql database

I am trying to insert an image from windows application to mysql database , it has been executed succesfully but there exists no data in my table.
Here I have used the following code. The execution is successful, according to my table email id and image must must be stored in table , but both the fields are saved as empty.
public void LoadImages()
{
MySqlConnection cn = new MySqlConnection(connstring);
cn.Open();
string image = txtLogo.Text;
byte[] ImageData;
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = BitConverter.GetBytes(fs.Length);
br.Close();
fs.Close();
MySqlParameter parImage = new MySqlParameter();
parImage.ParameterName = "?Images";
MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(?Images,'" + txtEmailIdText + "')", cn);
parImage.MySqlDbType = MySqlDbType.MediumBlob;
parImage.Size = 3000000;
parImage.Value = ImageData;//here you should put your byte []
cmd.Parameters.Add(parImage);
cmd.ExecuteNonQuery();
cn.Close();
}
BitConverter.GetBytes(fs.Length);
This returns the length as a byte[4], not reads the image data.
Take a look here for reading the file:
http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx
You probably also want to set parImage.Size to ImageData.length, not 3000000.

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);
}
}
}

Save and Load image SQLite C#

I'm trying to save and load images with SQLite with an app on WinForm with CF. I found a way to save an image into the db but I don't know if it's right because I couldn't find a way to load the image stored in the db.
I have a code to convert my image into a Base64:
public void ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format){
using (MemoryStream ms = new MemoryStream()){
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
SaveImage(base64String);
}
}
This is my code to save the image into the db:
void SaveImage(string pic){
string query = "insert into Table (Photo) values (#pic);";
string conString = #" Data Source = \Program Files\Users.s3db ";
SQLiteConnection con = new SQLiteConnection(conString);
SQLiteCommand cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add("#pic",DbType.String);
con.Open();
try{
cmd.ExecuteNonQuery();
}
catch (Exception exc1){
MessageBox.Show(exc1.Message);
}
con.Close();
}
I have a code to make the opposite of ImageToBase64 but first I need to load the image from the db. Any idea to do that?
EDIT I am trying to use the blob to save the image now as Charlie suggested. I tried this code:
Image photo = new Bitmap(#"\Photos\Image20120601_1.jpeg");
SaveImage(photo);
void SaveImage(Image pic){
string conString = #" Data Source = \Program Files\Users.s3db ";
SQLiteConnection con = new SQLiteConnection(conString);
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO Table (Photo) VALUES (#0);");
SQLiteParameter param = new SQLiteParameter("#0", System.Data.DbType.Binary);
param.Value = pic;
cmd.Parameters.Add(param);
con.Open();
try{
cmd.ExecuteNonQuery();
}
catch (Exception exc1){
MessageBox.Show(exc1.Message);
}
con.Close();}
But when I ExcecuteNonQuery() it catch an error of InvalidCastException.
Any suggest?
SOLUTION This code save an image into the database and then it load the image to show it in a pictureBox:
namespace ImagenSQLite
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Image photo = new Bitmap(#"\Photos\Image20120601_1.jpeg");
byte[] pic = ImageToByte(photo, System.Drawing.Imaging.ImageFormat.Jpeg);
SaveImage(pic);
LoadImage();
}
public byte[] ImageToByte(Image image, System.Drawing.Imaging.ImageFormat format){
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
}
//public Image Base64ToImage(string base64String)
public Image ByteToImage(byte[] imageBytes)
{
// Convert byte[] to Image
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = new Bitmap(ms);
return image;
}
/***************** SQLite **************************/
void SaveImage(byte[] imagen){
string conStringDatosUsuarios = #" Data Source = \Program Files\GPS___CAM\Data\DatosUsuarios.s3db ";
SQLiteConnection con = new SQLiteConnection(conStringDatosUsuarios);
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO Empleados (Foto) VALUES (#0);");
SQLiteParameter param = new SQLiteParameter("#0", System.Data.DbType.Binary);
param.Value = imagen;
cmd.Parameters.Add(param);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception exc1)
{
MessageBox.Show(exc1.Message);
}
con.Close();
}
void LoadImage(){
string query = "SELECT Photo FROM Table WHERE ID='5';";
string conString = #" Data Source = \Program Files\Users.s3db ";
SQLiteConnection con = new SQLiteConnection(conString);
SQLiteCommand cmd = new SQLiteCommand(query, con);
con.Open();
try
{
IDataReader rdr = cmd.ExecuteReader();
try
{
while (rdr.Read())
{
byte[] a = (System.Byte[])rdr[0];
pictureBox1.Image = ByteToImage(a);
}
}
catch (Exception exc) { MessageBox.Show(exc.Message); }
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
con.Close();
}
}
}
Thanks for your help!
To load the image from the database, you use a SQL select statement to get the data back, just like you would for any other kind of data. The base64-encoded image is stored as a string in the SQLite database. So you will retrieve it as a string, just like if you were storing any other string (like, for example, your name) in the database.
string LoadImage() {
string query = "select Photo from Table;";
string conString = #" Data Source = \Program Files\Users.s3db ";
SQLiteConnection con = new SQLiteConnection(conString);
SQLiteCommand cmd = new SQLiteCommand(query, con);
string base64EncodedImage = null;
con.Open();
try {
IDataReader reader = cmd.ExecuteReader();
reader.Read(); // advance the data reader to the first row
base64EncodedImage = (string) reader["Photo"];
reader.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
con.Close();
return base64EncodedImage;
}
Like your saving code, my example code to load the image uses only one image saved to the table. To load and save more than one image, you would need to insert an ID field into the table, and then use a where clause on your SQL select statement.
I'm not sure that I, personally, would store the image as a base64-encoded string. The string representation of the image will be much larger than the binary representation. SQLite supports the BLOB data type, so I would look into using that.
Here is sample Code in VB.net:
Imports System.IO
Imports System.Data.SQLite
Public Class Form1
'Image BLOB Functions:'
Private Function BlobToImage(ByVal blob)
Dim mStream As New System.IO.MemoryStream
Dim pData() As Byte = DirectCast(blob, Byte())
mStream.Write(pData, 0, Convert.ToInt32(pData.Length))
Dim bm As Bitmap = New Bitmap(mStream, False)
mStream.Dispose()
Return bm
End Function
'USE THIS FUNCTION TO CREATE A BLOB FROM AN IMAGE FILE'
Public Overloads Function ImageToBlob(ByVal id As String, ByVal filePath As String)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bm() As Byte = br.ReadBytes(fs.Length)
br.Close()
fs.Close()
'Create Parm'
Dim photo() As Byte = bm
Dim SQLparm As New SQLiteParameter("#image", photo)
SQLparm.DbType = DbType.Binary
SQLparm.Value = photo
Return SQLparm
End Function
'USE THIS FUNCTION TO CREATE A BLOB FROM AN IMAGE VARIABLE IN MEMORY'
Public Overloads Function ImageToBlob(ByVal id As String, ByVal image As Image)
Dim ms As New MemoryStream
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
'Create Parm'
Dim photo() As Byte = ms.ToArray()
Dim SQLparm As New SQLiteParameter("#image", photo)
SQLparm.DbType = DbType.Binary
SQLparm.Value = photo
Return SQLparm
End Function
'USE THIS SUB TO CREATE A DB AND TABLE'
Private Sub btnCreateDB_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLconnect As New SQLiteConnection()
Dim SQLcommand As New SQLiteCommand
SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
'SQL Query to Create Table'
SQLcommand.CommandText = "CREATE TABLE foo(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, image BLOB);"
SQLcommand.ExecuteNonQuery()
SQLcommand.Dispose()
SQLconnect.Close()
End Sub
'USE THIS SUB TO INSERT IMAGE INTO SQLITE DB. IT GETS AN id INTEGER FROM
Textbox1'
Private Sub btnInsertImage_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim d As New OpenFileDialog
d.Filter = "image (*.png)|*.png|(*.jpg)|*.jpg|All files|*.*"
If d.ShowDialog() = DialogResult.OK Then
Dim myimage As Bitmap = Clipboard.GetImage()
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As New SQLiteCommand
SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
'Insert Image, DO NOT single-quote #image'
SQLcommand.CommandText = "INSERT INTO foo (id,image) VALUES('" + TextBox1.Text + "', #image)"
'Define #image'
SQLcommand.Parameters.Add(ImageToBlob("#image", myimage))
SQLcommand.ExecuteNonQuery()
SQLcommand.Dispose()
SQLconnect.Close()
MessageBox.Show("Pic Inserted")
End If
End Sub
'USE THIS SUB TO GET THE BLOB FROM THE DB AND CONVERT IT BACK TO AN IMAGE'
Private Sub btnGetImageFromDB_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As New SQLiteCommand
SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT image FROM foo WHERE id = '" + TextBox1.Text + "'"
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
Dim myimage As Bitmap
While SQLreader.Read
myimage = BlobToImage(SQLreader("image"))
PictureBox1.Image = Nothing
PictureBox1.Image = myimage
End While
SQLcommand.Dispose()
SQLconnect.Close()
End Sub

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