I have implemented the following functionality that connects to webservice and downloads a favicon from a given site and saves it to a byte[] which I store in our database. I now want to set it up so that it saves the icon to the disk. However I am getting a "Parameter is not valid" when I try and create the image from the byte[].
我已经实现了以下连接到webservice并从给定站点下载favicon的功能,并将其保存到我存储在数据库中的byte []中。我现在想要设置它,以便将图标保存到磁盘。但是,当我尝试从byte []创建图像时,我得到“参数无效”。
My code is as follows..
我的代码如下..
stream.Write(imageByteArray, 0, imageByteArray.Length);
Image i = Image.FromStream(stream); // EXCEPTION HAPPENS HERE.
i.Save(@"C:\tmp\" + filename + ".ico");
The exception occurs on the middle line.
例外发生在中间行。
This code works perfectly 9 times out of ten, but for some favicons, even thought the icon is a valid image (or at least it appears to be and it shows in the browser when point at it) I get this exception.
这个代码在十分之一的情况下完美地运行了9次,但是对于某些favicons,甚至认为图标是有效的图像(或者至少它看起来是,并且当它指向它时它在浏览器中显示)我得到了这个例外。
Does anyone have any ideas? I am pulling my hair out here!
有没有人有任何想法?我在这里拔头发!
Thanks
谢谢
Dave
戴夫
Edit: The value in the array that appears to throw the error is 127.
编辑:出现抛出错误的数组中的值为127。
3 个解决方案
#1
20
There's no need to put it into an image, just spit the bytes straight out:
没有必要将它放入图像中,只需直接吐出字节:
var fs = new BinaryWriter(new FileStream(@"C:\\tmp\\" + filename + ".ico", FileMode.Append, FileAccess.Write));
fs.Write(imageByteArray);
fs.Close();
#2
1
I knew you had the answer you need but I just want to go on your original idea. I think the problem is your byte array somehow had been changed and become byte char array, you just need to add this code to make it become byte array again:
我知道你有你需要的答案,但我只是想继续你最初的想法。我认为问题是你的字节数组以某种方式被改变并成为字节字符数组,你只需要添加这个代码,使它再次成为字节数组:
for (int i=0;i<imageByteArray.Length;i++)
{
imageByteArray[i]=(byte) imageByteArray[i];
}
I had this problem and solved it by this solution. Good luck!
我有这个问题并通过这个解决方案解决了。祝你好运!
#3
0
Add image format:
添加图片格式:
stream.Position = 0;
i.Save(@"C:\tmp\" + filename + ".ico", System.Drawing.Imaging.ImageFormat.Icon);
#1
20
There's no need to put it into an image, just spit the bytes straight out:
没有必要将它放入图像中,只需直接吐出字节:
var fs = new BinaryWriter(new FileStream(@"C:\\tmp\\" + filename + ".ico", FileMode.Append, FileAccess.Write));
fs.Write(imageByteArray);
fs.Close();
#2
1
I knew you had the answer you need but I just want to go on your original idea. I think the problem is your byte array somehow had been changed and become byte char array, you just need to add this code to make it become byte array again:
我知道你有你需要的答案,但我只是想继续你最初的想法。我认为问题是你的字节数组以某种方式被改变并成为字节字符数组,你只需要添加这个代码,使它再次成为字节数组:
for (int i=0;i<imageByteArray.Length;i++)
{
imageByteArray[i]=(byte) imageByteArray[i];
}
I had this problem and solved it by this solution. Good luck!
我有这个问题并通过这个解决方案解决了。祝你好运!
#3
0
Add image format:
添加图片格式:
stream.Position = 0;
i.Save(@"C:\tmp\" + filename + ".ico", System.Drawing.Imaging.ImageFormat.Icon);