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[].
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.
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.
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();
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!
Add image format:
stream.Position = 0;
i.Save(@"C:\tmp\" + filename + ".ico", System.Drawing.Imaging.ImageFormat.Icon);
精彩评论