我用C#编写了以下代码:
int maxSideSize = 125;
MemoryStream memory = new MemoryStream( File.ReadAllBytes( Path.GetFullPath( "test1.png" ) ) );
Image img = Image.FromStream( memory );
//Determine image format
ImageFormat fmtImageFormat = img.RawFormat;
//get image original width and height
int intOldWidth = img.Width;
int intOldHeight = img.Height;
//determine if landscape or portrait
int intMaxSide;
if ( intOldWidth >= intOldHeight ) {
intMaxSide = intOldWidth;
} else {
intMaxSide = intOldHeight;
}
if ( intMaxSide > maxSideSize ) {
//set new width and height
double percent = maxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32( percent * intOldWidth );
intNewHeight = Convert.ToInt32( percent * intOldHeight );
} else {
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
//create new bitmap
Bitmap bmpResized = new Bitmap( img, intNewWidth, intNewHeight );
//save bitmap to disk
string path = Path.Combine( "C:\\Temp", test1.png" ) );
bmpResized.Save( memory, fmtImageFormat );
img.Save( path );
//release used resources
img.Dispose();
bmpResized.Dispose();
} catch (Exception e) {
Console.Write( e.Message );
}上面的代码可以针对ASP.NET应用程序进行优化吗?
我认为,如果有1000个用户连接到我的网站,其中可能有20%的用户上传了超过125px (宽度和高度)的图片,那么应用程序可能会崩溃。
我的朋友推荐使用Canvas或Drawing2D库。如果已经存在一个文件,会发生什么?是否可以覆盖?
很抱歉问了这么愚蠢的问题。在这种情况下我需要一些建议。
发布于 2012-03-20 17:24:31
20%的用户不太可能在同一秒内上传一张图片。当然,您应该确保在上传图像时调整图像大小,而不是在提供服务时调整图像大小。更重要的是,如果您的服务器不能完成工作,它不会崩溃,但会将用户放入队列中,这将导致响应时间变慢。
请记住,如果你允许匿名用户上传图片,你可能会成为DOS攻击的目标,任何优化都无法阻止这一点。您应该添加主动检查上传是否合法的代码,并在出现问题时限制新的上传。
最后,如果代码确实如您所描述的那样,则根本不需要内存流,您可以在创建位图时直接从文件中读取,并在保存位图时直接保存到文件中。
您可以使用this constructor overload加载该文件,并使用此Save method overload保存它
发布于 2012-03-20 17:22:29
您可以使用此nuget包http://nuget.org/packages/Simple.ImageResizer
使用方法:https://github.com/terjetyl/ImageResizer
我利用了wpf类,它们在内存方面应该比旧的System.Drawing类更友好。
发布于 2012-08-17 20:36:37
上传文件时,在按钮上单击:
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
objImage.Save(SaveLocation,ImageFormat.Png);
lblmsg.Text = "The file has been uploaded.";public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}更多详细信息Click here
http://satindersinght.blogspot.in/2012/08/how-to-resize-image-while-uploading-in.html
https://stackoverflow.com/questions/9783999
复制相似问题