参数在保存位图时无效

时间:2014-08-05 09:11:10

标签: c# graphics bitmap memorystream

我正在使用以下代码调整图像大小:

private void ResizeImage(string path)
    {
        var maxWidth = 700;
        var ms = new MemoryStream(System.IO.File.ReadAllBytes(Server.MapPath(path)));
        var imgToResize = Bitmap.FromStream(ms);
        var sourceWidth = imgToResize.Width;
        var sourceHeight = imgToResize.Height;
        if (sourceWidth > maxWidth)
        {
            var nPercent = ((float)maxWidth / (float)sourceWidth);
            var newWidth = (int)(sourceWidth * nPercent);
            var newHeight = (int)(sourceHeight * nPercent);

            var newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
            using (Graphics graphics = Graphics.FromImage(newImage))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawImage(imgToResize, 0, 0, newWidth, newHeight);

            }
            imgToResize.Dispose();
            var codecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

            var encoder = System.Drawing.Imaging.Encoder.Quality;
            var encParams = new EncoderParameters(1);

            var encParam = new EncoderParameter(encoder, 60);
            encParams.Param[0] = encParam;
            newImage.Save(Server.MapPath(path), codecInfo, encParams);
        }
    }
private ImageCodecInfo GetEncoderInfo(ImageFormat format)
    {
        return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
    }

在最后一行[newImage.Save(...)]它抛出一个异常,说参数无效。 这到底出了什么问题?

1 个答案:

答案 0 :(得分:1)

您的new EncoderParameter(encoder, 60);无效。单个Int32没有签名。请改用60L