1

I'm trying to resize and safe a picture I've done some research and tried to get sommething working. Almost everythin works but the saving gaves me an invalid argument exception. This is what I have:

     private void ResizeImage(Image image) 
     {
        int maxWidth = 100;
        int maxHeight = 100;
        int imageWidth = image.Size.Width;
        int imageHeight = image.Size.Height;

        double maxRatio = (double)maxWidth / (double)maxHeight;
        double picRatio = (double)imageWidth / (double)imageHeight;

        Image newImage = null;
        if (maxRatio > picRatio && imageWidth > maxWidth) 
        {
            newImage  = new Bitmap(image, new System.Drawing.Size(Convert.ToInt32(maxWidth / picRatio), maxHeight));            
        }
        else if (maxRatio < picRatio && imageHeight > maxHeight) 
        {
            newImage = new Bitmap(image, new System.Drawing.Size(maxWidth, Convert.ToInt32(maxHeight / picRatio)));         
        }

         // Encoder parameter for image quality
        EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,1);

        // Jpeg image codec
        ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

        if(jpegCodec != null){
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            newImage.Save(@".\temp\pdf\photos\test.jpg",jpegCodec,encoderParams);
        }   
    }

    private ImageCodecInfo getEncoderInfo(string mimeType) 
    {
        // Get image codecs for all image formats
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

        // Find the correct image codec
        for (int i = 0; i < codecs.Length; i++) 
        {
            if (codecs[i].MimeType == mimeType) 
            {
                return codecs[i];
            }
        }
        return null;
    }

But when I try to run it, it gives me an invalid argument exception on newImage.save()

Arion
  • 31,011
  • 10
  • 70
  • 88
jorne
  • 894
  • 2
  • 11
  • 23
  • You should make max width and max height arguments and set them to 100 at default, because from the outside no one would expect it. – MrFox Mar 16 '12 at 21:31

1 Answers1

1

According to MSDN, encoder quality parameter should be a 64-bit (long) value. Change this line:

var qualityParam = new EncoderParameter(Encoder.Quality, 1);

to

var qualityParam = new EncoderParameter(Encoder.Quality, 1L);
vgru
  • 49,838
  • 16
  • 120
  • 201