Loading PictureBox Image From Database - c#

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

Related

C# Read the image from database and Save it to another database

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...
}
}
}

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

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

load picturebox image from database where image column may be null

there is the code for loading image from database and shows it in picture box. the problem is if there's no pic in a row it will encounter an error however i marked as allow nulls image column in database.
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));
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(sream);
}
}
you should check for DbNull.Value.
This should do the trick:
if (count > 0)
{
if (ds.Tables["Images"].Rows[count - 1]["Image"] != DbNull.Value){
var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
(MemoryStreamstream = new MemoryStream(data)
pictureBox1.Image= Image.FromStream(sream);
}
}
You marked column id DB to accept null value so DB handles it but you also need do handle null in your application (you cannot cast DbNull value).
Hint
While using any kind of Stream you should use Using statement to dispose Stream after usage.
FYI, you need to learn to use using blocks. This will ensure that the objects are Disposed of in a timely manner, even if an exception is thrown:
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
using (
var sql =
new SqlConnection(
#"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True")
)
{
using (
var cmd = new SqlCommand
{
Connection = sql,
CommandText =
"select Image from Entry where EntryID = #EntryID"
})
{
cmd.Parameters.AddWithValue(
"#EntryID",
Convert.ToInt32(textBox1.Text));
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(ds, "Images");
}
}
}
var imagesTable = ds.Tables["Images"];
var imagesRows = imagesTable.Rows;
var count = imagesRows.Count;
if (count <= 0)
return;
var imageColumnValue =
imagesRows[count - 1]["Image"];
if (imageColumnValue == DBNull.Value)
return;
var data = (Byte[]) imageColumnValue;
using (var stream = new MemoryStream(data))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
just check
if(ds.Tables["Images"].Rows[count - 1]["Image"]!=DbNull.Value)
{
//you code of execution
}
else
{
//display default image
}

Convert from binary data to an image control in ASP.NET

I have binary data of an image in my database, and I want to display it in an image control in ASP.NET. How? If it is impossible, please find another way to save it in the database and display it in an image control.
Create a regular HTML img element like so:
<img runat="server" id="image" />
And in code behind do this:
image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
Where imageBytes is a byte[].
You are done. The image will be displayed.
Most likely the image is being stored as a byte array in the database. If so, then you can use this:
public static System.Drawing.Image ByteArrayToImage(byte[] bArray)
{
if (bArray == null)
return null;
System.Drawing.Image newImage;
try
{
using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length))
{
ms.Write(bArray, 0, bArray.Length);
newImage = System.Drawing.Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
newImage = null;
//Log an error here
}
return newImage;
}
public Byte[] Ret_image(Int32 id)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbimage where imageid=#id";
cmd.Connection = con;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Byte[] ar = (Byte[])(dr[1]);
dr.Close();
cmd.Dispose();
return ar;
}
protected void Button2_Click(object sender, EventArgs e)
{
Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text));
String st = Server.MapPath("abc.jpg");
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(ar, 0, ar.Length);
fs.Close();
Image1.ImageUrl = "abc.jpg";
}
Use this event for the button click to retrieve image and call the Ret_Image method here.
In a generic handler (.ashx):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"]))
{
try
{
string ImageId = context.Request.QueryString["ImageId"].ToString();
ImageDataModel idm = new ImageDataModel();
byte[] ImageData = idm.getImageData(ImageId);
context.Response.ContentType = "image/JPEG";
context.Response.OutputStream.Write(ImageData, 0, ImageData.Length);
}
catch(Exception ex){}
}
}
}
SqlConnection con = new SqlConnection();
string _path;
Using SYstem.IO;
Using System.Data.SQLClient;
//convert Image to binary and save in DB
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
_path = openFileDialog1.FileName;
InsertInSQL(_path);
}
}
private void InsertInSQL(string _path)
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
string strQ = "insert into dbo.PicTBL(Pic)values(#p)";
SqlCommand command = new SqlCommand(strQ,con);
command.Parameters.AddWithValue("#p",ImageToBinary(_path));
con.Open();
command.ExecuteNonQuery();
con.Close();
}
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
//Convert Binary to imge and save in a folder
private void button1_Click_1(object sender, EventArgs e)
{
DataTable dt = Rimage();
foreach (DataRow row in dt.Rows)
{
byte[] b = (byte[])row["Pic"];
Image img = BinaryToImage(b);
img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
}
}
private Image BinaryToImage(byte[] b)
{
if (b == null)
return null;
MemoryStream memStream = new MemoryStream();
memStream.Write(b, 0, b.Length);
return Image.FromStream(memStream);
}
private DataTable Rimage()
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from dbo.PicTBL";
cmd.Connection = con;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
adp.Fill(dt);
return dt;
}

Categories

Resources