I have this code written in 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 );
}
Can, the above code, be optimized for ASP.NET application ?
I think that if 1000 users are connected to my site, and maybe 20% of them upload an image with over 125px (as width and height) then the application may crash.
My friend recommended to use Canvas or Drawing2D library. What’s happens if there already exists a file ? It is possible to overwrite ?
Sorry for stupid question. I need advices in this case.
It is highly unlikely that 20% of users will upload an image in the same second. Of course you should make sure that you resize the image when it is uploaded and NOT when it is served. What is more if your server cannot do the work it will not crash but will put the users in the queue which will lead to slow response times.
Keep in mind that if you let anonymous users upload pictures you could be a subject of DOS attack and no amount of optimization can prevent that. You should add code that actively checks if the upload is legitimate and throttle new uploads when there are problems.
Finally if the code is really what you describe you do not need the memory stream at all you can read directly from the file when you create a bitmap and save directly to the file when you save a bitmap.
You can load the file with this constructor overload and save it with this Save method overload