0

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

2 回答 2

3

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

另请参阅How to: Set JPEG Compression Level,例如,请参阅此 SO answer

于 2012-09-11T12:32:28.820 回答
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);
}
于 2012-09-11T12:56:14.590 回答