需要压缩服务器上的图像大小

时间:2015-10-23 11:54:16

标签: c# asp.net image

在优化代码以上传最小尺寸的图片时,我遇到了问题。

这是我正在使用的代码:

public bool GenerateThumbnail(Stream inputStream, string filePath, int targetWidth, int targetHeight, bool fixedWidthImage)
    {
        bool success = false;
        try
        {
            using (var image = Image.FromStream(inputStream))
            {

                FileInfo file = new FileInfo(filePath);
                var extension = file.Extension;

                float targetRatio = targetWidth / (float)targetHeight;
                int width = image.Width;
                int height = image.Height;
                float imageRatio = width / (float)height;

                int newWidth;
                int newHeight;
                if (targetRatio > imageRatio && !fixedWidthImage)
                {
                    newHeight = targetHeight;
                    newWidth = (int)Math.Floor(imageRatio * targetHeight);
                }
                else
                {
                    newHeight = (int)Math.Floor(targetWidth / imageRatio);
                    newWidth = targetWidth;
                }

                var thumbnailImg = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
                var graphics = Graphics.FromImage(thumbnailImg);

                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                graphics.DrawImage(image, imageRectangle);
                //thumbnailImg.Save(filePath, image.RawFormat);

                // Get an ImageCodecInfo object that represents the JPEG codec.
                ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == image.RawFormat.Guid);

                // Create an Encoder object for the Quality parameter.
                Encoder encoder = Encoder.Quality;

                // Create an EncoderParameters object. 
                EncoderParameters encoderParameters = new EncoderParameters(1);

                // Save the image as a JPEG file with quality level.
                EncoderParameter encoderParameter = new EncoderParameter(encoder, 25L);
                encoderParameters.Param[0] = encoderParameter;

                thumbnailImg.Save(filePath, imageCodecInfo, encoderParameters);
                success = true;
            }
        }
        catch (Exception)
        {
            success = false;
        }

        return success;
    }

另外,当我使用小尺寸图片上传(20 Kb)时,它会转换为(> 36 Kb)相同尺寸。

所以,基本上我需要优化我的代码以获得具有目标图像尺寸的最小尺寸(Kb)图像。我的首要任务是获得具有最佳图像质量的最小尺寸图像。

感谢。

0 个答案:

没有答案