0

我想在將圖像上傳到本地存儲之前調整圖像的分辨率。現在它將圖像保存爲全分辨率,我必須使用width="200" height="200"或aspx中的css標籤手動調整圖像大小。我想在存儲圖像之前縮小圖像的文件大小,因此在用戶通過按鈕上載圖像時調整圖像分辨率。我曾嘗試使用System.Drawing,並設置int imageHeight和int maxWidth被調整大小,但似乎無法讓它工作。在vb上傳之前調整圖像大小

任何人都知道如何做到這一點?

到目前爲止我的代碼是:

Protected Sub btn_SavePic_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_SavePic.Click 
    Dim newFileName As String 
    Dim SqlString As String 
    If fup_Picture.HasFile Then 
     Dim myGUID = Guid.NewGuid() 
     newFileName = myGUID.ToString() & ".jpg" 
     Dim fileLocationOnServerHardDisk = Request.MapPath("Picture") & "/" & newFileName 
     fup_Picture.SaveAs(fileLocationOnServerHardDisk) 
    End If 

回答

3

你並不需要先將該文件保存到磁盤,您可以在內存中調整它的大小。我使用類似下面的代碼來調整上傳到相冊的圖片大小。 HttpPostedFile對象有一個InputStream屬性,可以讓你獲得實際的流。 toStream可讓您將輸出流式傳輸到任何您想要的內容(響應,文件等)。它將確保圖片正確縮放以適應640或480寬的盒子。你可能想把它們放在配置文件中而不是硬編碼它們。

private void ResizeImage(Stream fromStream, Stream toStream) 
{ 
    const double maxWidth = 640; 
    const double maxHeight = 480; 

    using(Image image = Image.FromStream(fromStream)) 
    { 
     double widthScale = 1; 

     if(image.Width > maxWidth) 
     { 
      widthScale = maxWidth/image.Width; 
     } 

     double heightScale = 1; 

     if(image.Height > maxHeight) 
     { 
      heightScale = maxHeight/image.Height; 
     } 

     if(widthScale < 1 || heightScale < 1) 
     { 
      double scaleFactor = widthScale < heightScale ? widthScale : heightScale; 

      int newWidth = (int)(image.Width * scaleFactor); 
      int newHeight = (int)(image.Height * scaleFactor); 
      using(Bitmap thumbnailBitmap = new Bitmap(newWidth, newHeight)) 
      { 
       using(Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap)) 
       { 
        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; 
        thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; 
        thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 

        Rectangle imageRectangle = new Rectangle(0, 0, newWidth, newHeight); 
        thumbnailGraph.DrawImage(image, imageRectangle); 

        ImageCodecInfo jpegCodec = ImageCodecInfo.GetImageEncoders() 
         .FirstOrDefault(c => c.FormatDescription == "JPEG"); 
        if(jpegCodec != null) 
        { 
         EncoderParameters encoderParameters = new EncoderParameters(1); 
         encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); 

         thumbnailBitmap.Save(toStream, jpegCodec, encoderParameters); 
        } 
        else 
        { 
         thumbnailBitmap.Save(toStream, ImageFormat.Jpeg); 
        } 
       } 
      } 
     } 
     else 
     { 
      image.Save(toStream, ImageFormat.Jpeg); 
     } 
    } 
} 
+0

+1。我刪除了我的答案,你的更好。 – 2012-01-06 19:06:56