My application saves image data in database and when loading information into form, it loads image into panel. This is working fine. But in case if user doesn't want to save image, I've inserted '0' in image field (varbinary) in database. While loading this information (0x00000000) from database it throws the following exception:
"Parameter is not valid."
Here I am giving some pieces of code:
Saving image in database:
if(user has selected an image)
{
Byte[] imageBytes = File.ReadAllBytes(imagePatient);
sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images
}
else
{
sqlCommand.Parameters.AddWithValue("Img", 0);
}
Loading image from database:
Byte[] imageData = new Byte[0];
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]);
MemoryStream stream = new MemoryStream(imageData);
panelImage.BackgroundImage = Image.FromStream(stream);
I've tried to put some check which will allow to load BackgroundImage if and only if data is not of the zeros form.
Please tell me how can I solve this issue?
I would store a NULL instead of 0.
if(user has selected an image)
{
Byte[] imageBytes = File.ReadAllBytes(imagePatient);
sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images
}
else
{
sqlCommand.Parameters.Add("Img", SqlDbType.VarBinary, -1 );
sqlCommand.Parameters["Img"].Value = DbNull.Value;
}
And then use an if statement to check if it's non-null:
Byte[] imageData = new Byte[0];
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]);
if(imageData != null)
{
MemoryStream stream = new MemoryStream(imageData);
panelImage.BackgroundImage = Image.FromStream(stream);
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
Related
am having a problem when i attempt to update a Record image in the DB.
the workflow am using goes as follows :
the user loads the image to a picture box using FilaDialog.
DialogResult path = openFileDialog1.ShowDialog();
if (path == DialogResult.OK)
{
pictureBox.Image = new Bitmap(openFileDialog1.FileName);
pictureBox.Refresh();
}
after the user finishes inserting the remaining fields and attempts to save the Image is loaded from the PictureBox and saved to the db.
Image img = PictureBox.Image;
byte[] photo_aray = null;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
}
so far so good, but the problem occurs when i attempt to update the Image which follows as such :
the user selects the Record from a list, an event loads Record information, image is loaded to a PictureBox.
after the user finishes updating the remaining fields and attempts to save the Image is loaded from the PictureBox and saved to the db using the same logic written above with some changes to the SQL query.
Image img = PictureBox.Image;
byte[] photo_aray = null;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg); // BREAKING POINT
photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
}
Every time the user attempts to update, the following error message is shown :
A generic error occurred in GDI+.:: at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
note that if the user changes the image or simply choose the same image using the Filedialog no error occurs.
any help is appreciated.
****** EDIT #1 *********
just to clarify,
records are first loaded from the database into RecordsList object which is bound to a List.
when a user selects a certain record, the Image is loaded from the Selected Record to the PictureBox.
if no changes are made to the picture , the image is loaded from picturebox to the logic explained above.
Thanks to Mr. #Jimi , I've managed to solve the issue.
as he so kindly pointed out, i need to dispose of the Memory stream after saving the object.
so my code was edited like this :
Image img = PictureBox.Image;
byte[] photo_aray = null;
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
//
//
//SQL UPDATE HERE
//
//
ms.Close();
ms.Dispose();
Thanks!
I have an image string contain in an XML file and want to convert the string into an image. I have used the following code which is giving error: Parameter is not valid.
Code is following which is give above error:
Byte[] data = new Byte[0];
byte[] array = Encoding.ASCII.GetBytes("D:\notimg.txt");
MemoryStream mem = new MemoryStream(array);
pictureBox1.InitialImage = null;
pictureBox1.Image = Image.FromStream(mem);
Below is the data contained in XML tag which I need to convert into the image and display into picture box, I have placed the below data into a notepad file and removed the XML tag . Please, anyone, guide how to display the below data into an image. Thanks in advance.
<photograph>/9j/4AAQSkZJR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csA49RSuBZ80g4Kqw/I07tvjOR3HcVSEmMN1/pUgf8AjTgjqKdwLKzbSCDwavRyCWPb0PashmzkgY3c49DU0EpRgc0MDuvBuo+VLJA7YyQMHpXbtd26j5pUX/eOK8aW7ltnE8LFGPBI7e9Oi1CfzDIJnDk5LE5Jouw1PY47y2lbakyMR6GrFeRw63fRtzMWHowyK6TSvE7p8jnHoGPy/wD1qaYJncUVTtL2O5UbflbGdpPb1B7irlUUgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooqreXSWdpJO7BVRc5Jo2Fexna1qSWNpJIxG2PgDP3m7D8K8mvbvzJ5JnYu7nOSa0df1t9Um2odsMfTPc9ya52TG/nJrNa6krUa8vOf6Uwle/HvTWbsKYSTTGPLxjsW/HFAc5wFA96YBk+n1qTAUcc0gsOyxPapETPXg01flALbgPYU/wA4IRsBB9xmqDYRo2QZ2Fu9K0kQQgR4z69qYJJSSFC/yqMXbq3Qj2IyKWwD12gZ2kD+8vOKcueiPuBpquGOUOxsdu/4U/y2XGR15BFK4xsg5+dcEUi5Qe3oalXdnnml8vPNK4WIjjqBipFbB46U4Rd6csXQY5ouOwh42jtyRTgnzcdKVozwOmKkRe350XsFhwOUIPpTF4OAasqi46HNQSIQSF4+lCkKxLFICQA+D71bjlIPzZ+orMC4PuPep4d+OOcenWqFY6Kx1i4tCmx9yqcgZxiu+0fWIdTh+VgJUHzLXlCSEY7+xFX7DUJbOdZoppRRVDR//2Q==</photograph>
Quick and dirty:
var s = File.ReadAllText(#"d:\file.txt");
s = s.Replace("<photograph>", string.Empty).Replace("</photograph>", string.Empty);
var b = Convert.FromBase64String(s);
using (var mem = new MemoryStream(b))
{
pictureBox1.Image = Image.FromStream(mem);
}
It's Base64
first convert to byte[]
then use
public System.Drawing.Image Base64ToImage(byte[] imageBytes)
{
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
then You Will Got image..!:)
I am working on a Window Form application in C# using VS2012. I am getting error in the below code:
if (dt.Rows[0]["Photo"] != System.DBNull.Value) //Retrieve image into PictureBox from database
{
photo_aray = (byte[])dt.Rows[0]["Photo"]; //where photo_aray is byte[] photo_aray;
MemoryStream ms = new MemoryStream(photo_aray);
ms.Seek(0, SeekOrigin.Begin);
Pic.Image = Image.FromStream(ms); //Where Pic is the pictureBox(Error is getting in this line of "Invalid Parameter")
}
I used below code to convert image into byte code and save into "Photo" column of database of image datatype:
if (Pic.Image != null)
{
ms = new MemoryStream();
Pic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
}
sqlcommand cmd = new sqlcommand("INSERT into tbData (Photo) VALUES (photo_aray)",con);
cmd.ExecuteNonQuery();
Please help if anyone knows. Thank You
I want to retrieve image from SQL Server(Database) using Entity Framework and set it to PictureBox Image Property
I have maked a user control & inherit it to PictureBox (Name:DisplayImage)
public static void LoadDisplay(Guid? DisplayID, string Name, byte[] image)
{
DisplayImage objDisplayImage = new DisplayImage();
DisplayList.Add(objDisplayImage);
objDisplayImage.Name = Name;
MemoryStream ms = new MemoryStream(image);
Image myImage = Image.FromStream(ms);
objDisplayImage.Image = myImage;
objDisplayImage.DisplayID = DisplayID;
PlayerForm.Instance.Controls.Add(objDisplayImage);
}
but Image is not loading on PictureBox
Try this code
try
{
// get image from object
byte[] _ImageData = new byte[0];
_ImageData = (byte[])_SqlRetVal;
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ImageData);
_Image = System.Drawing.Image.FromStream(_MemoryStream);
}
catch (Exception _Exception)
{
// Error occurred while trying to create image
// send error message to console (change below line to customize error handling)
Console.WriteLine(_Exception.Message);
return null;
}
i've tried the following code for loading an image in picturebox from database. but everytime , i get an error like 'paramater is not valid'.
buttonSave()
{
.......
.......
img = Image.FromFile(strFileName);
byte[] byteImg = ImageToByteArray(img);
objEmp.Picture = byteImg;
.......
.......
}
public byte[] ImageToByteArray(Image img)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
Display()
{
.......
.......
Byte[] bytePicData = (Byte[])dt.Rows[0]["PICTURE"];
MemoryStream stmPicData = new MemoryStream(bytePicData);
PicBox.Image = Bitmap.FromStream(stmPicData);}
.......
.......
}
the image is corrupt. The error is from the FromStream method. Can you write to disk and see if you can open it in an image view. If not then check the code where you are inserting it into the database
Byte[] bytePicData = (Byte[])dt.Rows[0]["PICTURE"];
// Save
File.WriteAllBytes("out.bmp", bytePicData);
MemoryStream stmPicData = new MemoryStream(bytePicData);
PicBox.Image = BitMap.FromStream(stmPicData);