C# “参数无效”异常加载 System.Drawing.Image

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/629955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:01:26  来源:igfitidea点击:

"Parameter not valid" exception loading System.Drawing.Image

c#imagestreamargumentexception

提问by

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 byteArrayInis 169014. I am getting this exception despite the fact that no value in it is greater than 255.

的长度byteArrayIn为 169014。尽管其中没有任何值大于 255,但我收到此异常。

回答by Marc Gravell

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[].

哪一行抛出异常?的new MemoryStream(...)?或Image.FromStream(...)?什么是byteArrayIn?是byte[]吗?我只是因为评论“并且其中没有任何价值不大于 255”而询问-这对于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);

回答by Jon Skeet

My guess is that byteArrayIndoesn't contain valid image data.

我的猜测是byteArrayIn不包含有效的图像数据。

Please give more information though:

请提供更多信息:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayInfrom, and are you sure it should contain a valid image?
  • 哪行代码抛出异常?
  • 消息是什么?
  • byteArrayIn从哪里得到的,你确定它应该包含一个有效的图像?

回答by Sebastian

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:

我遇到了同样的问题,现在显然已经解决了,尽管这和其他一些 gdi+ 异常非常具有误导性,但我发现实际上问题是发送到位图构造函数的参数无效。我有这个代码:

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.

文件流是根据从地图服务器下载的文件构建的。我的应用程序错误地发送请求以获取图像,服务器返回带有 jpg 扩展名的内容,但实际上是一个 html,告诉我发生了错误。所以我正在拍摄那个图像并尝试用它构建一个位图。修复方法是控制/验证有效 jpeg 图像的图像。

Hope it helps!

希望能帮助到你!

回答by Sam

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.

抛出的“参数无效”异常Image.FromStream()告诉您该流不是“有效”或“已识别”格式。观察内存流,尤其是当您从文件中获取各种字节偏移量时。

// 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.

示例 2 将起作用,请注意 useEmbeddedColorManagement 必须为 false 才能使 validateImageData 有效。

May be easiest to debug by dumping the memory stream to a file and inspecting the content.

通过将内存流转储到文件并检查内容可能是最容易调试的。

回答by gandarmin

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;

回答by Mriganka..THE CODER..

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..:

给出的所有解决方案都不起作用..不要只专注于检索部分。luk 插入图像。我犯了同样的错误。我从硬盘中提取图像并将其保存到数据库中。问题在于插入命令。luk 在我的故障代码..:

 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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

100% 保证在检索时不会出现 PARAMETER NOT VALID 错误....已解决!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!

回答by GPGVM

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:

大多数情况下,发生这种情况的都是 SQL 列中的错误数据。这是插入图像列的正确方法:

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'))

回答by Savas Adar

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);

回答by Nirbhay Singh

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();