有关图像大小调整方法 gdi 的帮助

本文关键字:方法 gdi 帮助 调整 图像 | 更新日期: 2023-09-27 17:56:34

所以我需要一些调整大小。

我找到了两种不同的方法。

一个看起来像这样:

public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) {
        using(imageFile){
            Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight);
            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) {
                newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution);
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

另一个:

    public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) {
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        int NewHeight = originalImage.Height * width / originalImage.Width;
        if (NewHeight > maxHeight) {
            // Resize with height instead
            width = originalImage.Width * maxHeight / originalImage.Height;
            NewHeight = maxHeight;
        }
        System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);
        return newImage;
    }

我基本上"借用"了这两种方法,只是改变了零碎的东西。

但是 - 使用第一个,每当我调整为更小的图片时,文件的大小实际上比原始文件大(!?

第二个虽然大大改善了尺寸看起来很糟糕:/

如果可能的话,我当然倾向于在第一种方法中仅提高图像质量,但我看不出从我的角度来看,一切看起来都是"高质量"的?

有关图像大小调整方法 gdi 的帮助

您可能需要设置 JPEG 压缩级别。目前,它可能以非常高的质量水平保存,这可能不是您想要的。

有关更多信息,请参见此处:http://msdn.microsoft.com/en-us/library/bb882583.aspx

但请注意,仅降低图像的分辨率并不一定会减小文件大小。由于压缩的工作方式,由于插值模式而模糊的较小分辨率文件可能比原始文件大得多,尽管使用 JPEG 可能不是大问题,因为有损算法。但是,如果原始文件以前非常简单(如"平面"网络漫画或简单的矢量图形)并且在调整大小后变得模糊,那么对于 PNG 可能会产生巨大的影响。

无论文件大小问题如何,我都绝对建议您使用第一种方法,而不是带有GetThumbnailImage的方法。

GetThumbnailImage实际上会从源图像中提取嵌入的缩略图(如果存在)。不幸的是,这意味着如果您没有预料到并考虑嵌入的缩略图,您将从一些未知的原始文件大小和质量(与原始文件相比)进行缩放。这也意味着,您在一次运行(使用嵌入式缩略图)中获得的结果质量与在另一次运行(没有嵌入缩略图)中获得的结果质量大不相同。

我已经多次使用与您的第一种方法类似的东西,虽然我偶尔会看到您所看到的,但结果始终更好。