我希望在将图像上传到本地存储之前调整图像的分辨率。现在它以完整的分辨率保存图像,我必须使用width="200" height="200"
或aspx中的css标记手动调整图像大小。我想在存储之前减小图像的文件大小,因此当用户通过按钮上传图像分辨率时,可以调整图像分辨率。我之前尝试过使用System.Drawing并将int imageHeight和int maxWidth设置为调整大小但似乎无法使其工作。
任何人都知道如何做到这一点?
到目前为止我的代码是:
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
答案 0 :(得分: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 );
}
}
}