Parameter is not valid Exception while displaying image from database - c#

I know this question has been asked many times, but my problem is not being solved.
I inserted image to database and data type of my field is image. But I am trying to display the image in picture box this exception occurs.
Parameter is not valid.
Here is my code:
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] Img = (byte[])dr["imgImage"];
MemoryStream MS = new MemoryStream(Img);
MS.Seek(0, SeekOrigin.Begin);
//System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
//System.Drawing.Image img = (System.Drawing.Image)converter.ConvertFrom(Img);
pictureBox1.Image = Image.FromStream(MS);
}

i guess it works.
PCT.Image= Image.FromStream(ms);
is that works?
edit1:
////sql connection codes here
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] picture = (byte[])dr[0];
MemoryStream ms = new MemoryStream(picture, 0, picture.Length);
ms.Write(picture, 0, picture.Length);
RegPicture = Image.FromStream(ms, true);
pictureBox1.Image = RegPicture;
}
////sql connection codes here

Related

Get varbinary image into C# DataSet with SqlDataReader

SqlDataAdapter has the .Fill(dataset) function, but SqlDataReader doesn't.
This should extract the image and place it inside my byte[]
while (reader.Read())
{
listOfProfiles.Add(new Profile
{
ProfileImage = (byte[])profileReader["imageFile"]
});
I've tried to create a DataSet and create a row where the image should be
DataSet ds = new DataSet();
byte[] MyData = new byte[0];
DataTable table0 = new DataTable("table0", "table0");
table0.Columns.Add("imageFile"); // DB column name
table0.Rows.Add(listOfProfiles[0].ProfileImage);
ds.Tables.Add(table0);
DataRow myRow;
After the image is in my DataSet, I tried converting it to a BitmapImage, but got the following error:
Unable to cast object of type 'System.String' to type 'System.Byte[]'.'
This is the code that should convert the varbinary image from the database to a BitmapImage:
if (ds.Tables[0].Rows.Count == 1)
{
myRow = ds.Tables[0].Rows[0];
MyData = (byte[])myRow["imageFile"];
MemoryStream stream = new MemoryStream(MyData);
stream.Write(MyData, 0, MyData.Length);
stream.Position = 0;
System.Drawing.Image img =
System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
hpProfileImage.Source = bi;
}
Any help is very appreciated
A working example of loading image from database in WPF
private void LoadLoggedInUsersDetails()
{
con.Open();
SqlCommand cmd2 = new SqlCommand("Select * from userinfo where ID='" + idStringHere + "'", con);
byte[] photo;
SqlDataReader dr2 = cmd2.ExecuteReader;
while (dr2.Read)
{
photo = (byte[])dr2(11);
MemoryStream strm = new MemoryStream(photo);
BitmapImage bi = new BitmapImage;
bi.BeginInit();
strm.Seek(0, SeekOrigin.Begin);
bi.StreamSource = strm;
bi.EndInit();
imageControl.ImageSource = bi;
}
con.Close();
}
A quick explanation : First i am declaring a byte[] variable.Then,as the SqlDatareader starts to read data from the database,the byte[] variable gets it's value from the datareader's specific column/cell.Then i declare a MemoryStream which reads the byte[].Now we declare a BitmapImage variable.BeginInIt and EndInIt are essential in this case.To make sure the Memorystream's position is at the beginning,we use strm.Seek(0, SeekOrigin.Begin).The bitmapImage uses that MemoryStream as a StreamSource.Finally we call EndInIt and do whatever we want to do with the bitmap , in this case,use it as a ImageBrush's ImageSource

Load varbinary bitmap from SQL Server CE into picturebox

I'm trying to load a pre-saved images from an SQL Server CE VarBinary column into a PictureBox.
The column content is a bitmap image stored in varbinary format.
MemoryStream ms = new MemoryStream();
byte[] outbyte = new byte[100];
Int32 ordinal = 0;
conn.Open();
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ordinal = reader.GetOrdinal("FaceStamp");//FaceStamp: VarBinary column storing Bmp.
outbyte = (byte[])reader[ordinal];
ms.Write(outbyte, 0, outbyte.Length);
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms);
}
conn.Close();
// Code below is the code I used to save the Bitmap image to the database
Bitmap bmi = cam.GetBitmap(); // Capture image from webcam which I've tested working.
ImageConverter converter = new ImageConverter();
byte[] byteArray = new byte[0];
byteArray = (byte[])converter.ConvertTo(bmi, typeof(byte[]));
insert.Parameters.AddWithValue("#image", byteArray);
insert.ExecuteNonQuery();
I get an error at the following line:
pictureBox1.Image = Image.FromStream(ms);
Saying
{"Parameter is not valid."}
Any tips?
Thank you.
I usually do the following when converting images saved as byte arrays:
byte[] outbyte = (byte[])reader[ordinal];
using (MemoryStream ms = new MemoryStream(outbyte))
{
Bitmap image = new Bitmap(ms);
pictureBox1.Image = image;
}
For converting the original image to a byte array you can take a look at this SO question.

Display an image stored in MySql database in BLOB format using c#

I am using the following function to store image in db
void SaveImage(byte[] image)
{
MySqlConnection con = new MySqlConnection(db);//new connection is made
con.Open();
string cmdText = "INSERT INTO Picture(RoomNo ,pic )VALUES ('" + RoomNo.Text + "',?Image)";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.Add("?Image", image);
cmd.ExecuteNonQuery();
}
In main I am calling the function like this
using (var ms = new MemoryStream())
{
picbox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
SaveImage(ms.ToArray());
}
I do not know how to display it in a picture box .. can any one help me???
Are you using Windows Forms? And you must Convert Byte array to Image for displaying it in Picture Box.
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
And how did you convert Image to byte array. I hope that problem not there. You can use:
private byte[] ImageToByteArray(string ImageFile)
{
FileStream stream = new FileStream(
ImageFile, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);
// Convert image to byte array.
byte[] photo = reader.ReadBytes((int)stream.Length);
return photo;
}
set your image picture box using Image method (FromStream)
yourPictureBox.Image = Image.FromStream(ms);

System.ArgumentException: Parameter is not valid [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
“Parameter not valid” exception loading System.Drawing.Image
I am inserting a image in the DB.
Here's my code
public class ImageUtils
{
const int sizeThumb = 69;
public static int uploadImage(int memberid, Image thumbimage)
{
MemoryStream stream = new MemoryStream();
thumbimage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] thumbbytes = stream.ToArray();
//int length = Convert.ToInt32(data.Length);
//byte[] thumbimage = new byte[length];
//data.Read(thumbimage, 0, length);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FMMImages"].ConnectionString);
SqlCommand command = new SqlCommand("update Images_temp set thumbimage = #thumbimage where memberid=#memberid", connection);
SqlParameter param0 = new SqlParameter("#thumbimage", SqlDbType.Image);
param0.Value = thumbbytes;
command.Parameters.Add(param0);
connection.Open();
object result = command.ExecuteScalar();
connection.Close();
if (result != null)
{
return System.Convert.ToInt32(result);
}
else
{
return 0;
}
}
aspx.cs where I'm calling the uploadimage
image CroppedWaterMarkImage
......
ImageUtils.uploadImage(memberid, CroppedWaterMarkImage);
Error in the uploadimage function:
MemoryStream stream = new MemoryStream();
thumbimage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] thumbbytes = stream.ToArray();
System.ArgumentException: Parameter is not valid.
Thanks
Sun
These guys encountered a similar problem with Images and MemoryStream() because of a memory leak:
http://blog.lavablast.com/post/2007/11/29/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx
This link was resolved by calling System.Drawing.Bitmap instead of System.Drawing.Image:
http://forums.asp.net/t/1705636.aspx/1
http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx
Either (memory leak/corruption and/or choice of API) could be applicable to your scenario.
Also make sure the image file is valid.

Saving and retrieving image in SQL database from C# problem

I used this code for inserting records in a person table in my DB
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Image img = Image_Box.Image;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
this.personTableAdapter1.Insert(NIC_Box.Text.Trim(), Application_Box.Text.Trim(), Name_Box.Text.Trim(), Father_Name_Box.Text.Trim(), DOB_TimePicker.Value.Date, Address_Box.Text.Trim(), City_Box.Text.Trim(), Country_Box.Text.Trim(), ms.GetBuffer());
but when i retrieve this with this code
byte[] image = (byte[])Person_On_Application.Rows[0][8];
MemoryStream Stream = new MemoryStream();
Stream.Write(image, 0, image.Length);
Bitmap Display_Picture = new Bitmap(Stream);
Image_Box.Image = Display_Picture;
it works perfectly fine but if i update this with my own generated Query like
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Image img = Image_Box.Image;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
Query = "UPDATE Person SET Person_Image ='"+ms.GetBuffer()+"' WHERE (Person_NIC = '"+NIC_Box.Text.Trim()+"')";
the next time i use the same code for retrieving the image and displaying it as used above . Program throws an exception
alt text http://www.freeimagehosting.net/image.php?3bb5f0d4b3.jpg][img]http://www.freeimagehosting.net/uploads/th.3bb5f0d4b3.jpg
So can any one tell me why i can't figure it out.
Query = "UPDATE Person SET Person_Image =#pic WHERE (Person_NIC = '" + NIC_Box.Text.Trim() + "')";
SqlCommand cmd = new SqlCommand(Query);
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = ms.GetBuffer();
cmd.Parameters.Add(picparameter);
db.ExecuteSQL(Query);
This thing worked with this code hurray lolz

Categories

Resources