//Resize the images to 400x400
const int bmpW = 400;
// New image target width
const int bmpH = 400;
// New Image target height
if (Image1.HasFile)
{
int newWidth = bmpW;
int newHeight = bmpH;
byte[] Pic = this.DataSource.Image1;
// Convert to image for resizing
Bitmap Img = null;
Img = ((System.Drawing.Bitmap)(Bitmap.FromStream(new MemoryStream(Pic, 0, (Pic.Length - 1)))));
Bitmap newImg = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newImg.SetResolution(72, 72);
//newImg.SetResolution(400, 400);
// Get the uploaded image width and height
int upWidth = Img.Width;
int upHeight = Img.Height;
int newX = 0;
// Set the new top left drawing position on the image canvas
int newY = 0;
Decimal reDuce;
// Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
// to ensure the image is always in the center of the canvas vertically and horizontally
if ((upWidth > upHeight))
{
// Landscape picture
reDuce = Convert.ToDecimal(Convert.ToDecimal(newWidth) / Convert.ToDecimal(upWidth));
newHeight = Convert.ToInt32(upHeight * reDuce);
//newWidth = 400;
newY = Convert.ToInt32((bmpH - newHeight) / 2);
newX = 0;
// Picture will be full width
}
else if ((upWidth < upHeight))
{
// Portrait picture
reDuce = Convert.ToDecimal(Convert.ToDecimal(newHeight) / Convert.ToDecimal(upHeight));
//newHeight = 400;
newWidth = Convert.ToInt32(upWidth * reDuce);
newX = Convert.ToInt32((bmpW - newWidth) / 2);
newY = 0;
// Picture will be full hieght
}
else if ((upWidth == upHeight))
{
// square picture
reDuce = Convert.ToDecimal(Convert.ToDecimal(newHeight) / Convert.ToDecimal(upHeight));
newWidth = Convert.ToInt32(upWidth * reDuce);
newX = Convert.ToInt32((bmpW - newWidth) / 2);
newY = Convert.ToInt32((bmpH - newHeight) / 2);
}
// Create a new image from the uploaded picture using the Graphics class
// Clear the graphic and set the background color to white
// Use Antialias and High Quality Bicubic to maintain a good quality picture
// Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning
Graphics newGraphic = Graphics.FromImage(newImg);
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight);
MemoryStream stream = new MemoryStream();
newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
this.DataSource.Image1 = stream.ToArray();
// assign back to picture
stream.Close();
Img.Dispose();
newImg.Dispose();
newGraphic.Dispose();
}
The code published on the other replies in this tread have a problem when calculating the value of reDuce, e.g. reDuce = Convert.ToDecimal(Convert.ToDecimal(newWidth) / Convert.ToDecimal(upWidth));
The problem seems to be with dividing integers that must result in a decimal. I changed that bit and it now works fine.