如何在不改变图像原始高度、宽度的情况下压缩图像



我想使图像大小小于其原始大小。我使用以下代码来压缩图像大小,但它将图像大小从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;
        }

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

另请参阅如何:设置JPEG压缩级别,有关示例,请参阅此SO答案。

正如@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);
}