如何压缩图像而不改变c#中原始高度,图像宽度

时间:2012-09-11 12:28:25

标签: c# .net image system.drawing

我想让图像尺寸小于其原始尺寸。我使用以下代码来压缩尺寸图像,但它将图像尺寸从1MB增加到1.5MB
压缩大尺寸图像的任何其他解决方案,无需更改图像原始高度,宽度。

    public static byte[] CompressImage(Image img) {

            int originalwidth = img.Width, originalheight = img.Height;

            Bitmap bmpimage = new Bitmap(originalwidth, originalheight);

            Graphics gf = Graphics.FromImage(bmpimage);
            gf.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            gf.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear;
            gf.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

            Rectangle rect = new Rectangle(0, 0, originalwidth, originalheight);
            gf.DrawImage(img, rect, 0, 0, originalwidth, originalheight, GraphicsUnit.Pixel);

            byte[] imagearray;

            using (MemoryStream ms = new MemoryStream())
            {
                bmpimage.Save(ms, ImageFormat.Jpeg);
                imagearray= ms.ToArray();
            }

            return imagearray;
        }

2 个答案:

答案 0 :(得分:3)

您可以在将文件保存为JPEG时设置质量级别,这大部分也直接与文件大小相关 - 质量越低,输出文件越小。

另请参阅How to: Set JPEG Compression Level,有关示例,请参阅this SO answer

答案 1 :(得分:0)

正如@BrokenGlass所说,您可以在 EncoderParameter 中指定压缩级别。如果您想尝试改变质量,这是一个片段:

public static void SaveJpeg(string path, Image image, int quality)
{
    //ensure the quality is within the correct range
    if ((quality < 0) || (quality > 100))
    {
        //create the error message
        string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
        //throw a helpful exception
        throw new ArgumentOutOfRangeException(error);
    }

    //create an encoder parameter for the image quality
    EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
    //get the jpeg codec
    ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

    //create a collection of all parameters that we will pass to the encoder
    EncoderParameters encoderParams = new EncoderParameters(1);
    //set the quality parameter for the codec
    encoderParams.Param[0] = qualityParam;
    //save the image using the codec and the parameters
    image.Save(path, jpegCodec, encoderParams);
}