Retrieve Images from sql server database - c#

i am storing images to the database. How to retrieve all the images from the database.
Eg: select images from imagetable
Problem:
Data Logic:
while (dr.Read())
{
///Check for null
if (!dr.IsDBNull(0))
{
try
{
///Converting the image into bitmap
byte[] photo = (byte[])dr[0];
ms = new MemoryStream(photo);
Bitmap bm = new Bitmap(ms);
bmp[i] = bm;
ms.Close();
}
catch (Exception ex)
{
}
}
ASpx.CS page:
Bitmap[] bm= photos.GetImage();
for (int i = 0; i < bm.Length; i++)
{
MemoryStream ms = new MemoryStream();
**bm[i].Save(ms, ImageFormat.Jpeg);**(Error : A generic error occurred in GDI+.)
htmlCode.Append("<li><img ImageUrl=\\\"");
htmlCode.Append(**ms.GetBuffer()**);
htmlCode.Append("\" alt=\"\" width=\"100\" height=\"100\"></li>");
}
Image not getting displayed
Geetha

this is an example from Sql Server
connection.Open();
SqlCommand command1 = new SqlCommand("select imgfile from myimages where imgname=#param", connection);
SqlParameter myparam = command1.Parameters.Add("#param", SqlDbType.NVarChar, 30);
myparam.Value = txtimgname.Text;
byte[] img = (byte[])command1.ExecuteScalar();
MemoryStream str = new MemoryStream();
str.Write(img, 0, img.Length);
Bitmap bit = new Bitmap(str);
connection.Close();
look here
http://www.akadia.com/services/dotnet_read_write_blob.html

For SQL Server 2008 onwards, FILESTREAM is almost certainly the way to go.
Please see: SQL Server 2005 - How do I convert image data type to character format

You need to get the binary data from the DB, and then stream the binary data to the browser as image.

You are setting the Url of the image to be the byte stream - you need to save the image to the hard drive and provide the location.
A much better way would be to set the image url to be a resource handler with parameters that could then retrieve the image from the database and return it as a stream to the browser.

Related

SqlDataReader: Read varbinary into byte array

I have a SQL Server table with a varbinary(max) column. I use it to store images in it. The images are selected with an OpenFileDialog, translated into a byte[] like this
public byte[] ConvertImageToByteArray(String filepath)
{
try
{
return File.ReadAllBytes(filepath);
}
catch (Exception)
{
throw;
}
}
and then stored into the database using this line of code:
sqlCmd.Parameters.Add("#image", SqlDbType.VarBinary).Value = image;
It looks like this stored in the database, so I guess all seems to work like expected.
Unfortunately I am unable to load the images back from the datatable.
I am using a SqlDataReader to do so:
DbSql db = new DbSql();
SqlDataReader dr = db.GetDataReader(sqlCmd);
if (dr.Read())
{
if (!dr.IsDBNull(1))
productName = dr.GetString(1);
if (!dr.IsDBNull(2))
identNumber = dr.GetString(2);
[...]
if (!dr.IsDBNull(23))
comment = dr.GetString(23);
if (!dr.IsDBNull(24))
{
byte[] image = dr.GetSqlBytes(24).Value; // <- This is where I try to grab the image
}
}
It seems like I am not able to create a proper byte[] with
image = dr.GetSqlBytes(24).Value;
because my next step is not able to turn it into an image again:
public Image ConvertImageFromByteArray(byte[] array)
{
try
{
MemoryStream ms = new MemoryStream(array);
return Image.FromStream(ms);
}
catch (Exception) { throw; }
}
EDIT:
When trying something like
pictureBox.Image = ConvertImageFromByteArray(image)
I get an error saying "Invalid parameter" (self translated, saying "Ungültiger Parameter" in german)
Anyone able to offer a solution?
Once you cast your varbinary(MAX) to a byte array
image = (byte[])dr[24];
Try this..
MemoryStream ms = new MemoryStream(image);
imagePictureBox.Image = System.Drawing.Image.FromStream(ms);
This is how I create the byte array...
if (File.Exists(sLogoName) == false)
throw new Exception("File Not Found: " + sLogoName);
FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
int streamLength = (int)sourceStream.Length;
Byte[] byLogo = new Byte[streamLength];
sourceStream.Read(byLogo, 0, streamLength);
sourceStream.Close();

Error with conversion codes from object to image [duplicate]

Why am I getting the exception "Parameter not valid" in my code:
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
The length of byteArrayIn is 169014. I am getting this exception despite the fact that no value in it is greater than 255.
I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:
using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
try
{
using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
{
try
{
bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
GC.Collect();
}
catch (Exception ex)
{
throw ex;
}
}
}
catch (ArgumentException aex)
{
throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
}
}
The following line was causing an error:
Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)
The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it.
The fix was to control/ validate the image for a valid jpeg image.
Hope it helps!
My guess is that byteArrayIn doesn't contain valid image data.
Please give more information though:
Which line of code is throwing an exception?
What's the message?
Where did you get byteArrayIn from, and are you sure it should contain a valid image?
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
The "parameter is not valid" exception thrown by Image.FromStream() tells you that the stream is not a 'valid' or 'recognised' format. Watch the memory streams, especially if you are taking various offsets of bytes from a file.
// 1. Create a junk memory stream, pass it to Image.FromStream and
// get the "parameter is not valid":
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);`
// 2. Create a junk memory stream, pass it to Image.FromStream
// without verification:
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms, false, true);
Example 2 will work, note that useEmbeddedColorManagement must be false for validateImageData to be valid.
May be easiest to debug by dumping the memory stream to a file and inspecting the content.
Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].
As a more obvious question: does the binary actually contain an image in a sensible format?
For example, the following (although not great code) works fine:
byte[] data = File.ReadAllBytes(#"d:\extn.png"); // not a good idea...
MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);
Console.WriteLine(img.Width);
Console.WriteLine(img.Height);
This error is caused by binary data being inserted into a buffer.
To solve this problem, you should insert one statement in your code.
This statement is:
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));
Example:
FileStream obj_FileStream = new FileStream(str_ImagePath, FileMode.OpenOrCreate, FileAccess.Read);
Byte[] Img = new Byte[obj_FileStream.Length];
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));
dt_NewsFeedByRow.Rows[0][6] = Img;
all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
//THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = #img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.Parameters.Add("#img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
da.UpdateCommand.Parameters["#img"].Value = photo;
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:
INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))
Most people do it incorrectly this way:
INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))
Just Follow this to Insert values into database
//Connection String
con.Open();
sqlQuery = "INSERT INTO [dbo].[Client] ([Client_ID],[Client_Name],[Phone],[Address],[Image]) VALUES('" + txtClientID.Text + "','" + txtClientName.Text + "','" + txtPhoneno.Text + "','" + txtaddress.Text + "',#image)";
cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.Add("#image", SqlDbType.Image);
cmd.Parameters["#image"].Value = img;
//img is a byte object
** /*MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();*/**
cmd.ExecuteNonQuery();
con.Close();

When I retrieve image from sql server 2008 r2 the image is black

I have write a program that on it i upload and download image to/from database SQL Server 2008 R2 .
I upload image using code below :
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = System.Data.SqlDbType.Image;
picparameter.ParameterName = "value";
picparameter.Value = val;//val is a byte array
SqlCommand sqlcommand = new SqlCommand("update " + table + " set " + col + " = #value "+" where "+where, sqlconnection);
sqlcommand.Parameters.Add(picparameter);
sqlcommand.ExecuteNonQuery();
I convert image from an PictureBox to array using code below:
public static byte[] ImageToByteArray(System.Drawing.Image img)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Bitmap b = new Bitmap(img);
b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
Then i download image from database to hard disk using code below :
Byte[] data = new Byte[0];
data = (Byte[])(imageReader["image"]);
MemoryStream mem = new MemoryStream(data);
Image.FromStream(mem).Save(Application.StartupPath + "\\Temp\\img\\" +imageReader["code"].ToString() + ".png",
System.Drawing.Imaging.ImageFormat.Png);
But, I have a big problem images back ground makes black after save them from database to hard disk.
You're saving as jpeg:
b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
But loading as png:
Image.FromStream(mem).Save(..., ImageFormat.Png);
Not 100% sure that's your issue but it looks problematic.

Converting binary data to image in C#

I was stuck with how to retrieve an image from MySQL database and convert it from Binary format to Bitmap Image to display it in ASP:Image or HTML Image. I am able to upload image but its being converted to Binary data and I couldn't understand how to convert it back to Bitmap format :(
protected void Button2_Click(object sender, EventArgs e)
{
cmd = new OdbcCommand("SELECT picture from profile limit 1", MyConnection);
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
Response.Write("No rows");
}
if(dr.Read())
{
// WHAT TO CODE HERE?
}
}
Anybody please help me in fill the code with WHAT TO CODE HERE part.
If you modify this method, it should do the trick:
public BitmapImage ConvertToImage(System.Data.Linq.Binary binary)
{
byte[] buffer = binary.ToArray();
MemoryStream stream = new MemoryStream(buffer);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
Add "PresentationCore " dll from add reference to get System.Windows.Media.Imaging dll referred inorder to get rid of the missing ref error... :)

Converting System.Byte[] to the image and display in the picturebox in winform

I have a table where the picture has been stored and while loading the form i retrieve that data and data is in System.Byte[].
I want this to display in the picture box in window form.
I am using C# language and SQL SERVER 2005
my code goes like this :
Byte[] byteBLOBData = (Byte[])(dt.Rows[count]["stud_photo"]);
MemoryStream ms = new MemoryStream(byteBLOBData);
ms.Write(byteBLOBData, 0, byteBLOBData.Length);
photo.Image = Image.FromStream(ms); --- here i am having an error "Parameter not valid"
Please can anyone help me ...Its very important for my project. Thank you in advance
Set stream position back to the beginning:
ms.Write(byteBLOBData, 0, byteBLOBData.Length);
ms.Position = 0; // THIS !!!!!
photo.Image = Image.FromStream(ms);
The problem is the stream position is at the end so when Image tries to read it, it will read zero byte.
MemoryStream ms = new MemoryStream(byteBLOBData);
Position is indeed your problem. However, the constructor already initializes the memory stream, you don't have to call Write(). Just delete it and the Position will be okay as well.
you need to remove the header of an image and then get the image data and add the code below to return image after only getting image data.
public Image byteArrayToImage(byte[] byteBLOBData )
{
MemoryStream ms = new MemoryStream(byteBLOBData );
Image returnImage = Image.FromStream(ms);
return returnImage;
}
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand(Query, cnn);
MemoryStream stream = new MemoryStream();
cnn.Open();
byte[] image = (byte[])cmd.ExecuteScalar();
stream.Write(image, 0, image.Length);
cnn.Close();
Bitmap bitmap = new Bitmap(stream);
pictureBox1.Image = bitmap;

Categories