C# Error : Unable to insert record in SQL - c#

Please pardon my knowledge on C# as I am very new to it,I am unable to insert a record in SQL and getting the below error while insert image to SQL.
Error :
Object reference not set to an instance of an object.
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
If i select a image and insert it inserts successfully, but if i do not select an image it throws the above error.
Please help!!

Change this:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
To this
MemoryStream ms = new MemoryStream();
pictureBox1?.Image?.Save(ms, pictureBox1?.Image?.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("#img", (object)img ?? DBNull.Value);

Try testing that PictureBox1.Image exists before referencing it, like this:
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("#img", img);
}
else
{
com.Parameters.Add("#img", SqlDbType.VarBinary, 0).Value = DbNull.Value;
}
EDITED to include comment by GarethD

first, you need to make a new condition to check is file selected or not.here are code below:
if pictureBox1.hasfile == true
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
}
because you are not selecting any file thats why it throwing exception on runtime

Related

Parameter is not valid when selecting image from SQL Server database

I'm facing an issue when trying to select an image field from the SQL server.
Here's the select code:
string cmd = String.Format("SELECT TOP 1 * FROM {0}", DefTableNames.Employees.ToString());
DataTable data = SQLDataQueryToTable(FullServerPath(), cmd);
CurrentEditingIndex = int.Parse(data.Rows[0][0].ToString());
empNameDropDown.SelectedItem = empNameDropDown.Items[0];
empNameTxt.Texts = data.Rows[0][1].ToString();
empIdTxt.Texts = data.Rows[0][2].ToString();
empPhoneTxt.Texts = data.Rows[0][3].ToString();
empEducationTxt.Texts = data.Rows[0][4].ToString();
empJobNameTxt.Texts = data.Rows[0][5].ToString();
TextTools.Currencize(data.Rows[0][6].ToString(), empTotalAllTxt);
empAboutTxt.Texts = data.Rows[0][7].ToString();
empBirthDatePicker.Value = DateTime.Parse(data.Rows[0][8].ToString(), CultureInfo.InvariantCulture);
empJobDatePicker.Value = DateTime.Parse(data.Rows[0][9].ToString(), CultureInfo.InvariantCulture);
Console.WriteLine(data.Rows[0][10]);
image_employeeimage.Image = byteArrayToImage((byte[])data.Rows[0][10], null);
if (image_employeeimage.Image != null)
{
buttonDeleteImage.Enabled = true;
buttonDeleteImage.BackColor = Color.Brown;
}
else
{
buttonDeleteImage.Enabled = false;
buttonDeleteImage.BackColor = AColors.DisabledColor;
}
empUserDropDown.SelectedItem = data.Rows[0][11].ToString();
The code fills everything in properly, however, it keeps stopping at the method for conversion of the data to an image.
Here's the conversion code:
public static Image byteArrayToImage(byte[] byteArrayIn, Image defaultImage = null)
{
if (byteArrayIn == null)
{
return defaultImage;
}
Image returnImage;
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
returnImage = Image.FromStream(ms);
}
return returnImage;
}
The code stops exactly at here:
Here's the code that converts to byte[]:
public static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
When I try to do a Console.WriteLine for the value of the image, I get the proper value. Which is System.Byte[].
The type of column in the database is set to VarBinary.
What exactly am I doing wrong?
I found my problem. The issue was pretty dumb:
public static byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
I was saving the image as a gif. Which when I changed to this:
public static byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, imageIn.RawFormat);
return ms.ToArray();
}
Fixed the entire issue.
And I also found a big problem in the save code. I was defining the size of the data as 255. This also led to the images not loading at times or loading as null. This was in the original code that I didn't share:
if(image_employeeimage.Image == null)
{
sqlParams.Add(new SqlParameter("#image", SqlDbType.VarBinary, 255)); sqlParams[9].Value = DBNull.Value;
}
else
{
sqlParams.Add(new SqlParameter("#image", SqlDbType.VarBinary, 255)); sqlParams[9].Value = imageToByteArray(image_employeeimage.Image);
}
I simply removed 255.
Everything seems fine now. Thanks a lot for the help everyone, and thanks for the tips on my code.
If there are any comments on my fix, please share them.

How can I save a PictureBox graphics object to a Stream? [duplicate]

i wanna save a picture that loaded in a picturebox to stream .when i save in png format it work properly but when i want save it in other formats i get
A Generic error occured in GDI + exception
its my code:
Image Img = pictureBox1.Image;
byte[] inputImage = new byte[Img.Width * Img.Height];
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Read(inputImage, 0, Img.Width * Img.Height);
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(Img.RawFormat))
{
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
}
else if (System.Drawing.Imaging.ImageFormat.Png.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
}
Try this method:
public Stream ImageToStream(Image image, System.Drawing.Imaging.ImageFormat format)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, format);
return ms;
}
and use it:
using(Stream stream = ImageToStream(pictureBox1.Image,
System.Drawing.Imaging.ImageFormat.Gif))
{
...
}

C# byte array to Image

I need to create an Image from a Byte Array but I don't know how to do this. I tried to do it like this:
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
But there was always the message that the parameter ms is not valid.
The exact Exception message is:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
With this I am reading the Array from the database
byte[] bytes = ObjectToByteArray(reader["profilepicture"]);
private byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Can anybody please help me with this problem?
Try this:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Source

Cannot implicitly convert type 'void' to 'byte[]'

The image is meant to be added to an update sql statement to update the image id a user changes the picture. I am trying to call the displayPhoto method into the savebtn method and assign it to residentImage variable as the image placeholder.
PhotoDisplay Method:
private void DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
}
Save Button Method:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
hello.addtionalInformation = txtAdditionalInformation.Text;
hello.FirstName = txtForename.Text;
hello.Surname = txtSurname.Text;
hello.Title = txtTitle.Text;
hello.ResidentID = GlobalVariables.SelectedResident.ResidentID;
hello.Doctor.DoctorID = GlobalVariables.SelectedResident.Doctor.DoctorID;
hello.Room.RoomID= GlobalVariables.SelectedResident.Room.RoomID;
hello.Room.Name = txtRoomNo.Text;
hello.Allergies = txtResidentAlergies.Text;
hello.Photo = DisplayPhoto(hello.Photo);
hello.DateOfBirth = DateTime.Parse(txtDOB.Text);
ResidentData.Update(hello);
}
You have defined your DisplayPhoto function to be a 'void' function, meaning that it returns nothing.
Then how do you expect to get something back in hello.Photo = DisplayPhoto(hello.Photo);?
If you want to read something back from DisplayPhoto, probably you need to write something like this
public byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
// .......
return stream.ToArray();
}
else
{
// Convert your existing ResidentImage.Source to a byte array and return it
}
}
You are trying to set hello.Photo to the return value of DisplayPhoto yet it's return type is void, e.g. it returns nothing at all. Problematic line is here:
hello.Photo = DisplayPhoto(hello.Photo);
You need to make DisplayPhoto return a byte[]. Crude example: -
private byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
return stream.ToArray();
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
return new byte[0];
}

How to Convert Byte[] to Image in asp.net?

public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
System.Drawing.Image returnImage = null;
try
{
MemoryStream ms = new MemoryStream(byteArrayIn);
returnImage = System.Drawing.Image.FromStream(ms); // parameter is invalid
}
catch (Exception ex)
{
string a = ex.ToString();
// Response.Write("sfdsfn");
}
return returnImage;
}
I did lot of search in Net but i cant get any useful answer for me?
any help..thanks in advance
Simple way Image.FromStream:
public Image byteArrayToImage(byte[] imgBytes)
{
using (MemoryStream imgStream = new MemoryStream(imgBytes))
{
return Image.FromStream(imgStream);
}
}
You can use new Bitmap(ms):
Image returnImage = null;
MemoryStream ms = new MemoryStream(byteArrayIn);
returnImage = new Bitmap(ms);
Similarly, you can use Bitmap.FromStream (oddly, I can't find documentation for it).
Took me 2 minutes to find this one :
ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(byteArray);

Categories

Resources