views:

201

answers:

1

So I was trying to convert a Bitmap image to JPEG in code and I keep getting this error:

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll

Additional information: Parameter is not valid.

Here is the related code. All the paths are correct and the EncoderParameter is not null, what else could be causing this?

ImageCodecInfo codecInfo = null;

foreach( ImageCodecInfo codec in  ImageCodecInfo.GetImageEncoders())
{
    if (codec.MimeType != "image/jpeg") { continue; }

    codecInfo = codec;
    break;
}

EncoderParameters encoderParameters = new EncoderParameters();
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 85);
using (Bitmap bitmapToConvert = new Bitmap(filePathIn))
{
    bitmapToConvert.Save(filePathOut, codecInfo, encoderParameters);
}
+2  A: 

Doh!

encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 85);

Should be:

encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 85L);
//OR
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)85);

In IL, 85 stays as an int, and the GDI backend doesn't like that, it wants a long. I hate non-descriptive exceptions.

Oh well, thanks for everybody's time.

Alex Moore