2011-06-22 11 views
4

我有一個形象如何在c#中調整圖像大小?

image = Image.FromStream(file.InputStream); 

我如何使用屬性System.Drawing.Size用於調整它們的大小或者用於此屬性?

我可以直接調整圖像的大小,而不必將其更改爲位圖或不損失任何質量。我不希望公司只是調整他們的大小。

我如何在C#中做到這一點?

回答

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