System.ArgumentException when calling Bitmap.Save(Stream, ImageCodecInfo, EncoderParameters)
I was building this small app to that collects images and stores them within a database. To do this you need to Save the bitmap your wanting to store as a memory stream within a blob data cell in a table.
As a base force source you can reference the following KB articles:
· Q317016 -How to read and write a file to or from a BLOB column by using ADO.NET and Visual C# .NET
These samples by themselves were enough since I also wanted to save my images at a slightly lower quality setting to conserve disk space. For that you need to use one of the overloaded Save methods of the Bitmap class. I was trying to use this one:
[C#] public void Save(Stream, ImageCodecInfo, EncoderParameters);
I found some sample code that looked like it was what I wanted:
Well, I came up with the code below (only the relevant portion is shown) but for the life of me I kept getting an exception that was frustrating the begeebers out of me: System.ArgumentException “Invalid Parameter Used”
Bitmap windowScreenShot = GetWindowPreview(new IntPtr(Explorer.HWND));
EncoderParameters eps = new EncoderParameters(1);
eps.Param[0] = new EncoderParameter(Encoder.Quality, 50);
ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
MemoryStream ms = new MemoryStream();
windowScreenShot.Save(ms, ici, eps);
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j)
{
if(encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
I think I spent a good forty minutes dorking around with this exception. If you notice, I am hard-coding the quality at 50% whereas all the references I found passed in the compression value as a long variable (see the code from Q324788).
Well, turns out the root of the problem is that the value of 50 gets compiled into IL as an integer (resulting in the Encoder constructor that accepts an int and not the one that takes a long) and Bitmap.Save complains when the Quality EncoderParameter is of this type. So, to fix this issue all I had to do was cast the 50 to a long, everything turned kosher.
eps.Param[0] = new EncoderParameter(Encoder.Quality, 50L)
All my frustration for one little character!!!! These are the worst, when you’re seemingly the 1st person to encounter a given issue or no one’s documented seeing this before. Nothing in the KB about this error, nothing in the newsgroups, I even hit nilch on Google.
Hopefully this post will clear that up!
Comments
- Anonymous
July 10, 2004
I ran into that one also! - Anonymous
July 10, 2004
The comment has been removed