Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can resize the image in c#?

Tags:

c#

asp.net-mvc

I have an image

image = Image.FromStream(file.InputStream);

How I can use the property System.Drawing.Size for resize them or where this property used for?

Can I direct resize the image without change them to bitmap or without loss any quality. I not want corp just resize them.

How I can do this in C#?

like image 308
Anirudha Gupta Avatar asked Jan 20 '23 10:01

Anirudha Gupta


1 Answers

This is a function I use in my current project:

    /// <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;
    }
like image 81
thomasvdb Avatar answered Jan 28 '23 16:01

thomasvdb