0

这一切都在 C# 中:

我正在使用此代码来调整图像的大小:

_image = (Image)new Bitmap(_refImage, _width, _height);

_refImage 只是一个参考图像,与原始图像相同,因此如果我多次调整大小,分辨率不会混乱。

如果我使图像更大,则此代码可以正常工作,它会按预期拉伸它。

但是,如果我使图像更小,那么它只会切断边缘。

我只是调整宽度,因为我只想改变宽度。

4

2 回答 2

1

我找到了一个可能有效的链接:Here。希望有帮助。

于 2012-06-16T22:02:52.813 回答
0

试试这个:

        /// <summary>
        /// Scales to within given boundaries - Aspect ratio is kept. High Quality Bi-Cubic interpolation is used.
        /// If boundary is larger than the image, then image is scaled up; if smaller, it is scaled down.
        /// </summary>
        /// <param name="originalImg">Image: Image to scale</param>
        /// <param name="width">Int: Restriction on width for output size. Must be greater than zero</param>
        /// <param name="height">Int: Restriction on height for output size. Must be greater than zero</param>
        /// <param name="backgroundColour">Color: Colour to shade background behind image</param>
        /// <returns>Image: Scaled Image</returns>
        /// <exception cref="ArgumentException">[ArgumentException] Boundary dimensions must exceed zero</exception>
        public static Image ScaleToFit(Image originalImg, int width, int height, Color backgroundColour)
        {
            if (originalImg == null) return null;
            if (width < 1 || height < 1) throw new ArgumentException("ScaleToFit: Boundary dimensions must exceed zero.");

            var destX = 0;
            var destY = 0;
            float nPercent;

            var nPercentW = (width / (float)originalImg.Width);
            var nPercentH = (height / (float)originalImg.Height);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = Convert.ToInt16((width - (originalImg.Width * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = Convert.ToInt16((height - (originalImg.Height * nPercent)) / 2);
            }

            var destWidth = (int)(originalImg.Width * nPercent);
            var destHeight = (int)(originalImg.Height * nPercent);

            var bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(originalImg.HorizontalResolution, originalImg.VerticalResolution);

            var grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(backgroundColour);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(originalImg,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(0, 0, originalImg.Width, originalImg.Height),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }

注意:这会保持纵横比,如果你想足够容易地倾斜它,你可以改变它。

于 2012-06-16T22:09:04.227 回答