Saturday, March 10, 2012

Resize image when uploading (C#)

This is the way you need to reduce the image size....
By default i reduced the size of the image to 200 X 400
U can chang eit
 
 
private Bitmap ResizeImage(Stream streamImage)
{ 
    int maxWidth = 200;
    int maxHeight = 400;
Bitmap originalImage = new Bitmap(streamImage);
    int newWidth = originalImage.Width;
    int newHeight = originalImage.Height;
    double aspectRatio =  
(double)originalImage.Width / (double)originalImage.Height;

    if (aspectRatio <= 1 && originalImage.Width > maxWidth)
    {
        newWidth = maxWidth;
        newHeight = (int)Math.Round(newWidth / aspectRatio);
    }
    else if (aspectRatio > 1 && originalImage.Height > maxHeight)
    {
        newHeight = maxHeight;
        newWidth = (int)Math.Round(newHeight * aspectRatio);
    }

    Bitmap newImage =  
new Bitmap(originalImage, newWidth, newHeight);
    
    Graphics g = Graphics.FromImage(newImage);
    g.InterpolationMode = 

System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
    g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

    originalImage.Dispose();
    
    return newImage;     
}
 

No comments:

Post a Comment