3

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

2 Answers 2

26

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

Sign up to request clarification or add additional context in comments.

5 Comments

In VB I've been using a standard 32bit Integer for the quality value without issues.
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#.
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?
Thanks, this would have taken some time to figure out on my own
"Clunky" sounds like a better word to describe this; my first reaction was that I've encountered a bug!
4

You should cast quality value to long, like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.