Working with images: Parameter is not valid

What I suggest that is more correct when you save the image is

ImageCodecInfo myImageCodecInfo = FindJpegEncoder();

EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, cQuality);

imgFinal.Save(TheFileNameTosaveIt, myImageCodecInfo, encoderParameters);

and this the function to find the Encoder from the system

internal static ImageCodecInfo FindJpegEncoder()
{
    // find jpeg encode text
    foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders())
    {
        if (info.FormatID.Equals(ImageFormat.Jpeg.Guid))
        {
            return info;
        }
    }

    Debug.Fail("Fail to find jPeg Encoder!");
    return null;
}

where the long cQuality = 65L and be sure that is long, and I think that actually only thinks must change, the int to long on the function call. Also is better to warp with using(){} the functions that need dispose()

Follow up

You have a bug on the NewImage that you try to save, you do not get it from the actually graphics that you made before, that why nothing is change. The actually code of you did not save the create image but you make a new one, so this code

System.Drawing.Image imgFinal = (System.Drawing.Image)newImage;
newImage.Dispose();

imgFinal.Save(path, jpegCodec, encoderParams);
imgFinal.Dispose();

must be

newImage.Save(path, jpegCodec, encoderParams);
newImage.Dispose();

In my case, I was accidentally calling Dispose before Save which was resulting in the same "The parameter is not valid" error

Hope this helps!


I was able to fix this issue by specifying the datatype of the Quality. It must be a "long", therefore this solved my problem.

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$bmp = New-Object System.Drawing.Bitmap $imagePath

#Encoder parameter for image quality 
$myEncoder = [System.Drawing.Imaging.Encoder]::Quality
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1) 
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, [long]$quality)

# get codec
$myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'}

#save to file
$bmp.Save($imageOutPut,$myImageCodecInfo, $($encoderParams))

Without "long", the error was:

Exception calling "Save" with "3" argument(s): "Parameter is not valid."
At C:\Projects\Image_Comparison\ImageComparison.ps1:81 char:49
+     $bmp.Save($imageOutPut,$myImageCodecInfo, $($encoderParams))
+                                                 ~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException