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
Related
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.
I would like to extract word documents stored as image type fields in SQL and save each individual document in a local folder. The doc files stored in the image type data in sql, are special encoded OLEObjects.
I am trying with one first but I need to do the same for each record in the table. This is what I have done so far:
Byte[] bytData = null;
string constring = #"mystirngconnection";
SqlCommand command = new SqlCommand(#"SELECT LongDescription FROM SuUserReport
WHERE ProductId = 53 AND UserReportId = 31525");
command.CommandType = CommandType.Text;
SqlConnection myconn = new SqlConnection(constring);
command.Connection = myconn;
myconn.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
bytData = (byte[])dr["LongDescription"];
}
}
if (bytData != null)
{
FileStream fs = new FileStream("C:\\Temp\\Test1.doc",
FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write(bytData, 0, bytData.Length);
fs.Dispose();
}
I basically have two problems:
Reading this type of data it is very slow
Using the code above works for normal word documents however the information in my table has OLEObject encoded information, the code saves a word document but the information is only encoded characters
Previously, these images (word documents) where opened straightaway from SQL when the form was opened using an Access bound object frame linked to the longDescription image type field. The user could edit the document by double clicking on this special frame. The following code opens the document and makes it available to save changes:
With oleLongDescription
.Verb = acOLEVerbOpen 'In a separate window
.Action = acOLEActivate
End With
Could anybody be so kind as to help me out with this, please? I do not mind to use c# or vb as long as it works =).
Here is code that I use to open my blobs. the byte[] myarray is the blob field from the database, the fileext is the extension of the file you are creating and the filename is a name you give it. It deletes any previous file of this name.
public static string Openfilefrombyte(byte[] myarray, string fileext, string filename)
{
Computer myComputer = new Computer();
string filenamef = myComputer.FileSystem.SpecialDirectories.Temp + #"\" + filename + "." + fileext;
if (File.Exists(filenamef))
{
File.Delete(filenamef);
}
//save to file and open
FileStream myfs = new FileStream(filenamef, FileMode.CreateNew);
myfs.Write(myarray, 0, myarray.Length);
myfs.Flush();
myfs.Close();
myfs = null;
Process.Start(filenamef);
return "OK";
}
i basically have two problems:
Reading this type of data it is very slow
Answer : Yes Its Slowly But if You save The Image in sql database as VarBinary it will be Fast .
i am Using OpenFileDialog1 To Bring Image Or what You Want (Rar , Pdf .World ...)
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
Try
T4.Text = OpenFileDialog1.FileName
T5.Text = Path.GetExtension(OpenFileDialog1.FileName)
T7.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)
Catch ex As Exception
End Try
End If
Here My Code I used it To Save Data In My Sql database :
Dim SQLCON As New SqlConnection(MyDataBaseCon)
Dim CMD As SqlCommand
Try
CMD = New SqlCommand("Insert Into TBLAtach (ID,AtachName,AtachMain,AtachFile,AtachNM,AtachDT,AtachAdres) Values (#ID,#AtachName,#AtachMain,#AtachFile,#AtachNM,#AtachDT,#AtachAdres)", SQLCON)
SQLCON.Open()
CMD.Parameters.Add(New SqlParameter("#ID", SqlDbType.Int)).Value = Val(T1.Text)
CMD.Parameters.Add(New SqlParameter("#AtachName", SqlDbType.Int)).Value = Val(T2.Text)
CMD.Parameters.Add(New SqlParameter("#AtachMain", SqlDbType.Int)).Value = Val(T3.Text)
Dim FSTream As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Dim BNStream As New BinaryReader(FSTream)
Dim FAttach() As Byte = BNStream.ReadBytes(BNStream.BaseStream.Length)
CMD.Parameters.Add(New SqlParameter("#AtachFile", SqlDbType.VarBinary)).Value = FAttach
CMD.Parameters.Add(New SqlParameter("#AtachNM", SqlDbType.NVarChar, 50)).Value = T5.Text
CMD.Parameters.Add(New SqlParameter("#AtachDT", SqlDbType.NVarChar, 50)).Value = TD1.Text
CMD.Parameters.Add(New SqlParameter("#AtachAdres", SqlDbType.NVarChar, 250)).Value = T7.Text
CMD.ExecuteNonQuery()
SQLCON.Close()
FSTream.Close()
BNStream.Close()
MsgBox("Ok ", MsgBoxStyle.Information)
SearchID()
ClearTxT()
Catch ex As Exception
MsgBox(ex.Message)
SQLCON.Close()
WaitPic.Visible = False
End Try
Using the code above, saves a word document but the information is only encoded characters
Answer : To retrieve Data (Image,Pdf,RAR,...)
i am Using This Code :
Try
ItDataset.Clear()
Flt = "Select ID , AtachAdres + AtachNM AS 'Fname' , AtachFile from TBLAtach where ID = " & T1.Text & ""
ItDataset = GeneralDataManager.InquireData(ItDataset, Flt, "TBLAtach")
If Me.BindingContext(ItDataset, "TBLAtach").Count > 0 Then
Dim FName As String = ItDataset.Tables("TBLAtach").Rows(0).Item("Fname")
Dim FAttach() As Byte = CType(ItDataset.Tables("TBLAtach").Rows(0).Item("AtachFile"), Byte())
Dim FStream As New FileStream(FName.ToString, FileMode.OpenOrCreate, FileAccess.Write)
FStream.Write(FAttach, 0, (FAttach.Length))
Process.Start(FName)
FStream.Close()
End If
WaitPic.Visible = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
And Change Your Connection To Your Data Base Con Connection
i hope this Answer Is Good For You .
Thank You .
I stored a image as a byte[] array as blob datatype in MySQL, but I cant find proper way to read that same picture the other way in my asp.net application in image control. In the table "slike" there are 3 columns - image, imagename, brTablice - I was searching for an answer really long and yet didn't find any answers. Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Server=localhost;Uid=Aleksa;port=3306;Pwd=pass;Database=projekat_automobili;";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT image from slike where brTablice = 'BG-456-SD'", con);
con.Open();
MySqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//TextBoxJmbg.Text = DR1.GetString(DR1.GetOrdinal("jmbg"));
//TextBoxIP.Text = DR1.GetString(DR1.GetOrdinal("imeprezime"));
//TextBoxTel.Text = DR1.GetString(DR1.GetOrdinal("tel"));
byte[] imgg = (byte[])(DR1["image"]);
if (imgg == null)
{
MemoryStream mstream = new MemoryStream(imgg);
Image1.ImageUrl = System.Drawing.Image.FromStream(mstream).ToString();
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(imgg);
//Image1.ImageUrl = "";
}
else
{
MemoryStream mstream = new MemoryStream(imgg);
Image1.ImageUrl = System.Drawing.Image.FromStream(mstream).ToString();
}
}
con.Close();
}
this is part of project.
mysql table:
----------------------------
G_Picture| G_Picture_size |
----------------------------
0xsd/s45e| 9000 |
-----------------------------
uint FileSize = _sqldatareader.GetUInt32(_sqldatareader.GetOrdinal("G_Picture_size"));
byte[] rawData = new byte[FileSize];
_sqldatareader.GetBytes(_sqldatareader.GetOrdinal("G_Picture"), 0, rawData, 0, (Int32)FileSize);
MemoryStream ms = new MemoryStream(rawData);
__G_Picture.BackgroundImage = new Bitmap(ms);
Now you a bitmap picture.
hope this work.
I have a SQL Server (2008 R2) with an Image table, the table has a column with type image. I insert my Image into this column using
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into pm005.images(imageName, type, alt, img)" + " values (#Name, #ContentType, #Alt, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("#Alt", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
private Boolean InsertUpdateData(SqlCommand cmd)
{
// Open a connection the the SQL Server
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=sql-server;integrated security=SSPI;database=pm005";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
This i believe works fine, because the insert returns true, and i can see the data in the database.
However i cant for the life of me see how i'm supposed to get this image back out. Specifically what i want is to be able to call my web service, pass it the imageID and have the image (and only the image) returned to me. Much like its done with PHP. THis is the code im using now.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public System.Drawing.Image getImage(int imageID, string uName, string pword)
{
string str="";
try
{
SqlCommand cmd = getSQLCommand("SELECT img FROM pm005.images WHERE id="+imageID);
byte[] Img = (byte[])cmd.ExecuteScalar();
// Convert the image record to file stream and display it to picture control
str = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
fs.Write(Img, 0, Img.Length);
fs.Flush();
fs.Close();
}
catch
{
}
finally
{
}
System.Drawing.Image theImage = System.Drawing.Image.FromFile(str);
return theImage;
}
Which gives the error:
System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at System.Drawing.IntSecurity.UnsafeGetFullPath(String fileName)
at System.Drawing.IntSecurity.DemandReadFileIO(String fileName)
at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
at WebService2.Service1.getImage(Int32 imageID, String uName, String pword)
I've looked at so many tutorials, and not find any solid answer except "use PHP". If i have to i will, but surely there must be a way to do it in ASP.NET?
Try specifying the Full FilePath:
FileStream fs = new FileStream(#"C:\Temp\YourFile.jpg", FileMode.CreateNew, FileAccess.Write);
Edit:
Rather than using the File System it sounds like you want to do it in memory:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
...
System.Drawing.Image theImage = null;
try
{
SqlCommand cmd = getSQLCommand("SELECT img FROM pm005.images WHERE id="+imageID);
byte[] Img = (byte[])cmd.ExecuteScalar();
theImage = byteArrayToImage(Img);
}
catch
{
}
finally
{
}
return theImage;
}
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());