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;
}
Related
I used the stored procedure for saving pic to db before, now I want to save it without the stored procedure
is possible to directly save from PictureBox?
private void buttonsave_Click(object sender, EventArgs e)
{
Categoryentity categoryentity = new Categoryentity();
categoryentity.CategoryName = texboxcatname.Text;
categoryentity.Description = textBoxcatdesc.Text;
categoryentity.Picture = pictureBox1.Image;
Dbclass dbclass = new Dbclass();
long result = dbclass.insertcategory(categoryentity);
if (result > 0)
{
MessageBox.Show("inserted");
}
else
{
MessageBox.Show("failed");
}
}
private void buttonuploadpic_Click(object sender, EventArgs e)
{
//string imagelocation = "";
//try
//{
OpenFileDialog fdialog = new OpenFileDialog();
fdialog.Filter = "jpg files(*.jpg)|*.jpg| PNG files(*.png)|*.png| All Files(*.*)|*.*";
if (fdialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
imagelocation = fdialog.FileName.ToString();
pictureBox1.ImageLocation = imagelocation;
}
}
entity class
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
namespace Northwind.Entities
{
[Table ("Categories")]
public class Categoryentity
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public string Pic { get; set; }
public Image Picture { get; set; }
insertion fn
public class Dbclass
{
public long insertcategory(Categoryentity categoryentity)
{
using (var connection = DBLayer.ConnectionFactory())
{
long id = connection.Insert<Categoryentity>(categoryentity);
return id;
}
}
I can upload the image, but I don't know how to insert it properly. but when I was using the stored procedure, it was inserted successfully.
previous stored procedure
byte[] images = null;
FileStream fileStream = new FileStream(imagelocation, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
images = binaryReader.ReadBytes((int)fileStream.Length);
Dbclass dbclass = new Dbclass();
string maincon = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(maincon);
sqlcon.Open();
string query = "insert into Categories(CategoryName,Description,Picture) Values ('" + texboxcatname.Text + "','" + textBoxcatdesc.Text + "',#images)";
SqlCommand sqlCommand = new SqlCommand(query, sqlcon);
sqlCommand.Parameters.Add(new SqlParameter("#images", images));
int N = sqlCommand.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("saved");
For directly inserting the picturebox picture into the data table and reading the picture from the data table to the picturebox, you could try to refer to the following code.
using Dapper.Contrib.Extensions;
using System;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace insertimage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Add();
MessageBox.Show("saved");
}
internal void Add()
{
string constr = #"constr";
SqlConnection con = new SqlConnection(constr);
string sqlinsert = "insert into [dbo].[Category] ([Id],[Name],[Picture]) values (#Id,#Name,#Picture) ";
con.Open();
SqlCommand cmd = new SqlCommand(sqlinsert, con);
byte[] b;
Image img = pictureBox1.Image;
using (MemoryStream mStream = new MemoryStream())
{
img.Save(mStream, img.RawFormat);
b = mStream.ToArray();
}
cmd.Parameters.AddWithValue("#Id", texboxcatid.Text);
cmd.Parameters.AddWithValue("#Name", textBoxcatdesc.Text);
cmd.Parameters.AddWithValue("#Picture", b);
cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
string constr = #"constr";
SqlConnection con = new SqlConnection(constr);
string sql = "select * from [dbo].[Category]";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
byte[] by = null;
while (reader.Read())
{
by = (byte[])reader[2];
}
Image img = byteArrayToImage(by);
pictureBox2.Image = img;
}
public Image byteArrayToImage(byte[] bytesArr)
{
using (MemoryStream memstr = new MemoryStream(bytesArr))
{
Image img = Image.FromStream(memstr);
return img;
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog fdialog = new OpenFileDialog();
fdialog.Filter = "jpg files(*.jpg)|*.jpg| PNG files(*.png)|*.png| All Files(*.*)|*.*";
if (fdialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(fdialog.FileName, FileMode.Open, FileAccess.Read);
Image im = Image.FromStream(fs);
pictureBox1.Image = im;
}
}
}
[Table("Category")]
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Image Picture { get; set; }
}
}
The result :
You can use https://www.nuget.org/packages/Dapper.Contrib/.
And then use the below code to insert the record
Categoryentity obj = new Categoryentity ();
...
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Insert(obj) ;
}
we can use this code to insert picture from picturebox
before that declate image type as byte[] on entity class.
on buttonsave action
private void buttonSavemp_Click(object sender, EventArgs e)
{
empentity.PhotoPath = textBoxphotopath.Text;
Image image = pictureBoxphoto.Image;
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
}
empentity.Photo = data;
Dbclass dbclass = new Dbclass();
long result = dbclass.insertpicture(empentity);
if (result > 0)
{
MessageBox.Show("inserted succesfully");
}
else
{
MessageBox.Show("insertion failed");
}
and we can use the below code for get picture
System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = (Image)imageConverter.ConvertFrom(employeentity.Photo);
pictureBoxphoto.Image = image;
I´ve stream video on a pictureBox control, and I want to get image from PictureBox, to store on a table on SQL Server. PictureBox show stream but, PictureBox retrieve null.
What is wrong?
private void button1_Click(object sender, EventArgs e){
SqlConnection con = new SqlConnection("Data Source=IBM-PC\\SQLEXPRESS2;Initial Catalog=DBACCESS;Integrated Security=True");
if (cmrConductor.Image == null){
mensajeOK("Error");
}else{
MemoryStream ms = new MemoryStream();
cmrConductor.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
SqlCommand cmd = new SqlCommand("INSERT INTO tblUsers (fldCode, fldPic) VALUES (#fldCode, #fldPic)", con);
cmd.Parameters.AddWithValue("#fldCode", txtId.Text);
cmd.Parameters.AddWithValue("#fldPic", Pic_arr);
con.Open();
try{
int res = cmd.ExecuteNonQuery();
if (res > 0){
MessageBox.Show("insert");
}
}
catch (Exception ex){
MessageBox.Show(ex.Message);
}
finally{
con.Close();
}
}
}
You need to set your image field type as varbinary(MAX) and you need to convert your image into a byte array before inserting.
//Insert image
SqlCommand comm = new SqlCommand("Insert into ImageColumn values (#Image)")
comm.Parameters.AddWithValue("#Image", Converter.GetBytes(pictureBox.image));
//Retrieving image
pictureBox1.Image = Converter.GetImage(dataTable.Rows[0]["ImageColumn"])
//Converter class
class Converter
{
public static byte[] GetBytes(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
public static byte[] GetBytes(string path)
{
using (var ms = new MemoryStream())
{
Image img = Image.FromFile(path);
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
public static Image GetImage(byte[] buffer)
{
using (var ms = new MemoryStream(buffer))
{
return Image.FromStream(ms);
}
}
}
Here is the solution, thanks to this post Saving Panel as an Image. I just had to change PictureBox control by a Panel control.
private void button1_Click(object sender, EventArgs e){
SqlConnection con = new SqlConnection("Data Source=IBM-PC\\SQLEXPRESS2;Initial Catalog=DBACCESS;Integrated Security=True");
MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(cmrConductor.Width, cmrConductor.Height);
cmrConductor.DrawToBitmap(bmp, cmrConductor.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
SqlCommand cmd = new SqlCommand("INSERT INTO tblUsers (fldCode, fldPic) VALUES (#fldCode, #fldPic)", con);
cmd.Parameters.AddWithValue("#fldCode", txtId.Text);
cmd.Parameters.AddWithValue("#fldPic", Pic_arr);
con.Open();
try
{
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("insert");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
an error shows saying that I have invalid parameters for this code...
can anyone tell me whats wrong? Im supposed to get the image assigned to the clientID.
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand("SELECT clientImage FROM client WHERE clientID='" + label2.Text + "'", conn);
conn.Open();
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
byte[] imgg = (byte[])(myReader["clientImage"]);
if (imgg == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstream = new MemoryStream(imgg);
pictureBox1.Image = System.Drawing.Image.FromStream(mstream);
}
}
conn.Close();
}
This piece of code might come in handy. I have tried it.
byte[] imagedata = (byte [])dataGridView1[4, dataGridView1.SelectedRows[0].Index].Value;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(imagedata, 0, imagedata.Length))
{
ms.Write(imagedata, 0, imagedata.Length);
//Set image variable value using memory stream.
image = Image.FromStream(ms, true );
}
this code works. MySql Wamp.
using System.IO;
string appPath = Path.GetDirectoryName(Application.Executable) + #"/student Images/";
string imagename;
//put this code below to load form.
getimage();
if(File.Exist(appPath + imagename)
{
PictureBox1.Image = Image.FromFile(appPath + imagename);
}
else
{
PictureBox1.Image = Properties.Resources.Image_notfound;
}
private void getimage()
{
MySqlConnection connect = new MySqlConnection(con);
MySqlCommand cmd = new MySqlCommand("SELECT PictureName as 'pic' FROM userprofile where ID='" + datagrid.CurrentRow.Cells["ID"].ToString() + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
Try
{
MySqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
imagename = dr.GetString("pic");
}
dr.Close();
}
catch(Exception ee)
{
Console.WriteLine(ee.ToString());
}
finally
{
connect.Close();
}
Controller
using System.IO;
using (TESTDBEntities db = new TESTDBEntities())
{
// first create var
var item = (from d in db.Hunger_tbl_MainCategory select d).ToList();
return View(item); // your view
}
View
#model List<WebApplication1.Models.TEST_tbl_IMG`enter code here`>
#foreach (var item in Model)
{
<div class="cards-list">
<div class="card 1">
#{
var base64 = Convert.ToBase64String(item.CategoryImage);
var imgsrc = string.Format("data:image/png;base64,{0}", base64);
}
<div class="card_image"> <img src='#imgsrc'/></div>
</div>
</div>
}
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;
}
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());