如何在C#中调整图片大小?

4

我有一张图片

image = Image.FromStream(file.InputStream);

我如何使用属性System.Drawing.Size来调整大小,或者这个属性用于哪里?

我可以直接调整图像大小而不将它们更改为位图或不损失任何质量吗?我不想裁剪,只想调整大小。

我该如何在C#中实现这个功能?

2个回答

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;
    }

3

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