Size, Width和Height都是System.Drawing.Image的Get()属性; 我如何在c#运行时调整图像对象的大小?

现在,我只是创建一个新的图像使用:

// objImage is the original Image
Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));

当前回答

这将执行高质量的调整大小:

/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}

wrapMode.SetWrapMode(WrapMode.TileFlipXY) prevents ghosting around the image borders -- naïve resizing will sample transparent pixels beyond the image boundaries, but by mirroring the image we can get a better sample (this setting is very noticeable) destImage.SetResolution maintains DPI regardless of physical size -- may increase quality when reducing image dimensions or when printing Compositing controls how pixels are blended with the background -- might not be needed since we're only drawing one thing. graphics.CompositingMode determines whether pixels from a source image overwrite or are combined with background pixels. SourceCopy specifies that when a color is rendered, it overwrites the background color. graphics.CompositingQuality determines the rendering quality level of layered images. graphics.InterpolationMode determines how intermediate values between two endpoints are calculated graphics.SmoothingMode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing) -- probably only works on vectors graphics.PixelOffsetMode affects rendering quality when drawing the new image

保持纵横比是留给读者的练习(实际上,我只是不认为这个函数的工作是为您做这件事)。

此外,这是一篇很好的文章,描述了调整图像大小的一些陷阱。上面的函数将涵盖其中的大部分,但您仍然需要担心保存。

其他回答

不知道这有什么困难,做你正在做的,使用重载Bitmap构造函数来创建一个重新大小的图像,你唯一缺少的是转换回image数据类型:

public static Image resizeImage(Image imgToResize, Size size)
{
    return (Image)(new Bitmap(imgToResize, size));
}

yourImage = resizeImage(yourImage, new Size(50,50));

使用下面的函数和下面的例子来改变图像大小:

//Example : 
System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg");
System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100);

//image size modification unction   
public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight)
{

    Bitmap outputImage = null;
    Graphics graphics = null;
    try
    {
         outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
         graphics = Graphics.FromImage(outputImage);
         graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
         new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

         return outputImage;
     }
     catch (Exception ex)
     {
           return img;
     }
}

下面的函数将返回显示图像的新大小。这在这里可能没有帮助。但它将返回调整大小的显示矩形大小。

 public static  class ResizeImage
{
    /// <summary>
    /// Return new resized size to display the image
    /// </summary>
    /// <param name="srcrectanle">source rectangle of image or you can pass the bitmap and set the size accrodingly</param>
    /// <param name="initSize">initial size of the page to draw image</param>
    /// <returns></returns>
    public static SizeF getResizedRectangle(RectangleF srcrectanle, SizeF initSize)
    {
        float sw = srcrectanle.Width;
        float sh = srcrectanle.Height;
        float dw = initSize.Width;
        float dh = initSize.Height;
        float finalHeight, finalWidth;
        float Sourceratio = sw / sh;

        if (Sourceratio >= 1)
        {
            finalWidth = (int)dw;
            float ratio = sw / dw;
            finalHeight = (sh / ratio);
        }
        else
        {
            finalHeight = (int)dh;
            float ratio = sh / dh;
            finalWidth = (sw / ratio);
        }
        return new SizeF(finalHeight, finalHeight);


    }
}

调整大小并保存图像以适应宽度和高度,就像画布保持图像成比例

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Infra.Files
{
    public static class GenerateThumb
    {
        /// <summary>
        /// Resize and save an image to fit under width and height like a canvas keeping things proportional
        /// </summary>
        /// <param name="originalImagePath"></param>
        /// <param name="thumbImagePath"></param>
        /// <param name="newWidth"></param>
        /// <param name="newHeight"></param>
        public static void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight)
        {
            Bitmap srcBmp = new Bitmap(originalImagePath);
            float ratio = 1;
            float minSize = Math.Min(newHeight, newHeight);

            if (srcBmp.Width > srcBmp.Height)
            {
                ratio = minSize / (float)srcBmp.Width;
            }
            else
            {
                ratio = minSize / (float)srcBmp.Height;
            }

            SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio);
            Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height);

            using (Graphics graphics = Graphics.FromImage(target))
            {
                graphics.CompositingQuality = CompositingQuality.HighSpeed;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    target.Save(thumbImagePath);
                }
            }
        }
    }
}

注意:这将不适用于ASP。因为WebImage依赖于系统。Web,但在以前版本的ASP。我在Net中多次使用了这个片段,它很有用。

String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg";
var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
{
      var thumbnail = new WebImage(stream).Resize(80, 80);
      thumbnail.Save(ThumbfullPath2, "jpg");
}