Below this code is where i try to retrieve the image to my database and try to save it to another database. In the first image you will see the error that i encountered during the run time when i click that ok button. In the second image you will see that i already inserted the data with my retrieve image but i encountered that error (I see that the image is inserted but i don't know if that is the correct one)
In my employee_product table i have the "Image" column = image datatype
(This table is where i retrieve my image)
In my product_result table I have the same column and same datatype
(This table is where i inserted the retrieved image)
What i want to happen is to retrieve that image and when click the ok button it will save to my database also it will show to my datagridview
//My Code for Adding the image to my employee_product
private void btn_add_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
try
{
var ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] PhotoByte = ms.ToArray();
if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text))
{
MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (#Image, #Supplier, #Codeitem, #Itemdescription, #Date, #Quantity, #Unitcost)", con);
selectCommand.Parameters.AddWithValue("#Image", PhotoByte);
selectCommand.Parameters.AddWithValue("#Supplier", cbox_supplier.Text);
selectCommand.Parameters.AddWithValue("#Codeitem", txt_code.Text.Trim());
selectCommand.Parameters.AddWithValue("#Itemdescription", txt_item.Text.Trim());
selectCommand.Parameters.AddWithValue("#Date", date);
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.Parameters.AddWithValue("#Unitcost", txt_cost.Text.Trim());
selectCommand.ExecuteNonQuery();
MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txt_path.Clear();
pictureBox1.Image = null;
cbox_supplier.Items.Clear();
txt_code.Clear();
txt_item.Clear();
txt_quantity.Clear();
txt_cost.Clear();
_view.AddingProduct();
}
}
catch (Exception)
{
MessageBox.Show("Input image");
}
}
}
byte[] data;
public void display()
{
using (var con = SQLConnection.GetConnection())
{
SqlCommand selectTable = new SqlCommand("Select * from product_result ; ", con);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = selectTable;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
_view.ListProduct.DataSource = bSource;
sda.Update(dbdataset);
}
}
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
var selects = new SqlCommand("Select * from employee_product where Codeitem =#Codeitem ", con);
selects.Parameters.Add("#Codeitem", SqlDbType.VarChar).Value = _view.txt_code.Text;
SqlDataReader reader;
reader = selects.ExecuteReader();
while (reader.Read())
{
data = (byte[])reader["Image"];
}
reader.Close();
var selectCommand = new SqlCommand("Insert into product_result (Image, Code, Name, Price, Discount, Quantity) Values (#Image, #Code, #Name, #Price, #Discount, #Quantity)", con);
selectCommand.Parameters.AddWithValue("#Image", data);
selectCommand.Parameters.AddWithValue("#Code", _view.txt_code.Text);
selectCommand.Parameters.AddWithValue("#Name", _view.txt_name.Text.Trim());
selectCommand.Parameters.AddWithValue("#Price", _view.txt_price.Text.Trim());
selectCommand.Parameters.AddWithValue("#Discount", txt_discount.Text.Trim());
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.ExecuteNonQuery();
var select = new SqlCommand("Update employee_product set quantity = quantity - #Quantity where Codeitem= #Codeitem",con);
select.Parameters.AddWithValue("#Codeitem", _view.txt_code.Text);
select.Parameters.AddWithValue("#Quantity", txt_quantity.Text);
select.ExecuteNonQuery();
this.Close();
display();
}
}
You will see in this picture that image has a code. If user input another code it will get another image
You can save the image of the PictureBox to db like this....
MemoryStream getimagestream = new MemoryStream();
pictureBox1.Image.Save(getimagestream, _pb_photo.Image.RawFormat);
byte[] Imagedata = getimagestream.GetBuffer();
You can receive the image from db to picture box like this.
var ImagedataReceive = (byte[])reader["Image"];
var stream = new MemoryStream(ImagedataReceive);
pictureBox1.Image = Image.FromStream(stream);
You will need to provide a cell formatting method that puts the data into an image object the data gridview can use.
private void dgv_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].Name == "Image")
{
if (e.Value != null)
{
... convert byte[] to image...
}
}
}
Related
I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.
I'm trying to make this catalog app that display images with its "title" and "category" but I can't seem to display the image because of an error
on the line that says
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
This is the whole of my code. I need the solution so i can print the image with its corresponding details in a list view. Thank you.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Books");
comboBox1.Items.Add("Games");
comboBox1.Items.Add("Music");
}
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-4T5BLQ6\\SQLEXPRESS;Initial Catalog=CatalogDB;Integrated Security=True");
SqlCommand command = new SqlCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlDataReader dataReader;
DataTable dataTable = new DataTable();
MemoryStream stream1;
byte[] photo_array;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
int i = 0;
MemoryStream stream = new MemoryStream();
command.CommandText = "insert into EntryTable(Title,Category,Image) values('" + textBox1.Text + "','" + comboBox1.Text + "','" + pictureBox1.Image + "')";
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (i > 0)
{
MessageBox.Show("Saved new item in index" + i);
}
connection.Close();
MessageBox.Show("Made New Entry");
showData();
clear();
}
void clear()
{
textBox1.Clear();
pictureBox1.Image = null;
comboBox1.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images only. |*.jpg; *jpeg; *.png; *.gif; *.bmp;";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void showData()
{
connection.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(100 , 100);
command.Connection = connection;
command.CommandText = "SELECT * FROM EntryTable";
dataAdapter.SelectCommand = command;
dataTable.Clear();
dataAdapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
connection.Close();
}
}
}
Xoriel,
You need to be more specific about what you are asking on SO. Your original post only indicates that you have and error and that it is holding up your app development (welcome to coding). You don't even tell us what error you are getting.
Now you ask how to implement a try catch? You should do a bit of research on your own. As far as try catch, you can start Here.
Your code indicates a lack of understanding about how windows winforms are instantiated and their sequence of events. To me, this indicates that you will have further problems after this one is fixed, so I will add a try catch to your code. It will write the exception to your console.
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
try
{
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
Your true issue is the format in which you are storing the image to the database and the way in which you are retrieving it.
Regards,
Marc
I have created a table in which there is one column of type varbinary(max) to store the files.
What I want to do is that I want to show a pictureBox if that column is not null nad I have written this code:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"'";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
if (dr["file"] != null)
picturebox.Visible = true;
}
}
But still its showing the pictureBox on load event of this page even if the file column is null.
Furthermore I want to download this particular file from the table to a disc when the user clicks on the pictureBox.
One of the major rules of using any kind of database is never return data you don't need. With this in mind you should exclude rows with no image using the query rather than checking after the fact.
So:
"select file from sentmail where msg_id='"+id of a particular row+"' and file is not null"
Rather than:
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
Giving us:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"' and file is not null";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
using (var ms = new MemoryStream((byte[])dr["file"]))
picturebox.Image = Image.FromStream(ms);
picturebox.Visible = true;
}
}
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
To check if the column contains binary data or null, you can use
if(!dr.IsNull("attach"))
{
attachment.Visible = true;
}
Get image bytes
Byte[] bytes = (Byte[])dr["attach"];
Convert image bytes to image
Image image = null;
using (var ms = new MemoryStream(bytes))
image = Image.FromStream(ms);
Show the picture on the picturebox
picturebox.Image = image;
To save the image, on picturebox.Click event handler
picturebox.Image.Save(#"drive:/path/to/save/image.bmp");
Glad to help! Please remember to accept the answer if you found it helpful.
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);
}
}
}
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());