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