我如何在c#中调整图像大小?

时间:2011-06-22 10:43:23

标签: c# asp.net-mvc

我有一张图片

image = Image.FromStream(file.InputStream);

如何使用属性System.Drawing.Size来调整它们的大小或此属性的用途?

我可以直接调整图像大小而不将其更改为位图或不丢失任何质量。我不希望公司只是调整它们的大小。

我如何在C#中做到这一点?

2 个答案:

答案 0 :(得分:6)

这是我在当前项目中使用的功能:

    /// <summary>
    /// Resize the image.
    /// </summary>
    /// <param name="image">
    /// A System.IO.Stream object that points to an uploaded file.
    /// </param>
    /// <param name="width">
    /// The new width for the image.
    /// Height of the image is calculated based on the width parameter.
    /// </param>
    /// <returns>The resized image.</returns>
    public Image ResizeImage( Stream image, int width ) {
        try {
            using ( Image fromStream = Image.FromStream( image ) ) {
                // calculate height based on the width parameter
                int newHeight = ( int )(fromStream.Height / (( double )fromStream.Width / width));

                using ( Bitmap resizedImg = new Bitmap( fromStream, width, newHeight ) ) {
                    using ( MemoryStream stream = new MemoryStream() ) {
                        resizedImg.Save( stream, fromStream.RawFormat );
                        return Image.FromStream( stream );
                    }
                }
            }
        } catch ( Exception exp ) {
            // log error
        }

        return null;
    }

答案 1 :(得分:3)

您可以使用Bitmap类的构造函数来帮助,实际上Bitmap是Image的子类。

var image_16 = new System.Drawing.Bitmap(image, new Size(16, 16));

参考 - http://msdn.microsoft.com/en-us/library/system.drawing.size.aspx

通过GDI +技术能够找到更多进展

http://www.codeproject.com/KB/GDI-plus/imageresize.aspx