繁体   English   中英

如何在不更改C#中图像的原始高度,宽度的情况下压缩图像

[英]How compress image without change the original height ,width of image in c#

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM