将图片保存到硬盘

时间:2012-03-13 13:33:40

标签: c# image exception invalid-argument

我正在尝试调整大小并保护一张我已经做过一些研究的图片,并试图让一些人工作。几乎每一件事都有效,但是节省给我一个无效的争论例外。 这就是我所拥有的:

     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;
    }

但是当我尝试运行它时,它在newImage.save()上给了我一个无效的参数异常

1 个答案:

答案 0 :(得分:1)

根据MSDN,编码器质量参数应为64位(长)值。改变这一行:

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

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