views:

2679

answers:

3

Hi Im trying to save a bitmap jpg format with a specified encoding quality. However im getting an exception ("Parameter is not valid.") when calling the save method.

If i leave out the two last parameters in the bmp.save it works fine.

        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 16);
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
        string outfile = outputpath + "\\" + fileaddition + sourcefile.Name;
        bmp.Save(outfile,ici,eps );

        bmp.Dispose();
        image.Dispose();
        return true;
    }
    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;
    }
}

Thank you

+4  A: 

GDI+ is pretty flaky. You'll need to use 16L for the value or cast to (long).

Hans Passant
In VB I've been using a standard 32bit Integer for the quality value without issues.
Ady
That did it! Thank you very much
CruelIO
odd. must be a c# thing.
Ady
It is. The type of literal "16" is byte in C#, Integer in VB.NET. EncoderParameter has constructors that take byte, short and long, but not int. You'll get the right one in VB but not in C#.
Hans Passant
nobugz: No, that’s wrong. The standard says in §9.4.4.2 that “[i]f the literal has no suffix, it has the first of these types in which its value can be represented: `int`, `uint`, `long`, `ulong`.” It is *never* `byte`. Or maybe this is a bug in the Microsoft C# compiler?
Konrad Rudolph
A: 

Ive tried to add the Colordepth parameter, but i still get the same error

CruelIO
A: 

You should cast quality value to long, like this:

eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)16);
mahdi