如何压缩JPG图像?

4

我有一个大小为3300K的jpg图像格式。

我尝试压缩图片 => 所以我改变了图片的大小,但文件仍然非常大(约800K)

更改大小的方法代码:

    internal static Image resizeImage( Image imgToResize )
    {
        Bitmap b = new Bitmap( 300, 300 );

        using( Graphics g = Graphics.FromImage( ( Image )b ) )
        {
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.InterpolationMode = InterpolationMode.Low;

            g.DrawImage( imgToResize, 0, 0, 300, 300 );

            imgToResize.Dispose();
        }

        return ( Image )b;
    }

我必须压缩图片,即使图像质量低于原始图像。

我该如何做?

2个回答

10

mg = 图像

newsize = 高度和宽度

使用以下代码调用Resize函数

Bitmap mg = new Bitmap(strUploadPath);
Size newSize = new Size(Convert.ToInt32(DispMaxWidth), Convert.ToInt32(DispMaxHeight));
Bitmap bp = ResizeImage(mg, newSize);
if (bp != null)
bp.Save(strUploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);

private Bitmap ResizeImage(Bitmap mg, Size newSize)
        {
            double ratio = 0d;
            double myThumbWidth = 0d;
            double myThumbHeight = 0d;
            int x = 0;
            int y = 0;

            Bitmap bp;

            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
            Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myThumbHeight = Math.Ceiling(mg.Height / ratio);
            myThumbWidth = Math.Ceiling(mg.Width / ratio);

            //Size thumbSize = new Size((int)myThumbWidth, (int)myThumbHeight);
            Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
            bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - thumbSize.Width) / 2;
            y = (newSize.Height - thumbSize.Height);
            // Had to add System.Drawing class in front of Graphics ---
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            return bp;

        }

你有WPF应用程序的示例吗?我试图插入代码,但无法识别Bitmap和Size。 - B. Clay Shannon-B. Crow Raven

2

JPG图片已经被压缩过了。

您可以尝试使用不同的压缩算法或减少图像质量来减小图像的大小。

在这种情况下,尝试设置CompositingQualitySmoothingMode属性以获得更好(适合您)的值--也许还有其他属性可以帮助您。


我知道这已经是压缩格式了。但是还有可能提高压缩级别。我尝试修改CompositingQuality和SmoothingMode——这不会改变图像大小。 - Yanshof
所以,也许使用Graphics类是不可能的。尝试一些工具,比如InfraView或Paint.NET来压缩你的图像。如果其中一个可以更好地压缩你的图像,那么就找一个外部库(也许是ImageMagick.NET?)来从.NET代码中实现它。 - Grzegorz Gierlik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接