Reputation:
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.
Upvotes: 42
Views: 160348
Reputation: 1480
Image.FromStream() method from .NET Documents
Exceptions
ArgumentException : The stream does not have a valid image format.
OutOfMemoryException : The stream does not have a valid image format.
You can use validateImageData
parameter but it will still throw exception..
I noticed that the Image.FormStream()
method is only streaming properly if your byte array created from png
,jpg
etc. old extensions. I used an image with webp
an it throws exception. You have to convert to old formats like jpeg to use properly. there are several libraries for convert images.
I advice SixLabors.ImageSharp.Web
First
dotnet add package SixLabors.ImageSharp.Web
After install the library
var imageAsStream = new MemoryStream(imageasByteArray);
Image image = null;
try {
image = Image.FromStream(imageAsStream);
}
catch(ArgumentException) {
using var imageSharp = SixLabors.ImageSharp.Image.Load(new ReadOnlySpan<byte>(imageasByteArray));
imageAsStream = new MemoryStream();
imageSharp.Save(imageAsStream, new JpegEncoder());
image = Image.FromStream(imageAsStream);
}
Upvotes: 0
Reputation: 1
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();
Upvotes: -7
Reputation: 4262
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);
Upvotes: 9
Reputation: 1521
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!
Upvotes: 22
Reputation: 5619
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'))
Upvotes: -5
Reputation: 21
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;
Upvotes: 1
Reputation: 11
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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Upvotes: -2
Reputation: 126
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.
Upvotes: 7
Reputation: 1500385
My guess is that byteArrayIn
doesn't contain valid image data.
Please give more information though:
byteArrayIn
from, and are you sure it should contain a valid image?Upvotes: 16
Reputation: 1062745
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);
Upvotes: 3