My code:
Expand|Select|Wrap|Line Numbers
- public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
- {
- using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
- {
- Size newSize = CalculateDimensions(oldImage.Size, targetSize);
- using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
- {
- using (Graphics canvas = Graphics.FromImage(newImage))
- {
- canvas.SmoothingMode = SmoothingMode.AntiAlias;
- canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
- canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
- canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
- MemoryStream m = new MemoryStream();
- newImage.Save(m, ImageFormat.Jpeg);
- return m.GetBuffer();
- }
- }
- }
- }
- private static Size CalculateDimensions(Size oldSize, int targetSize)
- {
- Size newSize = new Size();
- if (oldSize.Width > oldSize.Height)
- {
- newSize.Width = targetSize;
- newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width);
- }
- else
- {
- newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height);
- newSize.Height = targetSize;
- }
- return newSize;
- }
Case 1: Images smaller than the thumbnailed size (small 100px, medium 250px, large 500px, and xlarge 700px respectivly) expand the width to the target size and the height gets chopped off.
Samples: Original, large, xLarge
Case 2: Images that are portrait and the width is smaller than the target size, expand the width to the target size and grow the height to meet the new width respectivly.
Samples: Original, large, xLarge
What I'm needing to do:
Case 1, If the width is smaller than the target size I want to keep the existing width, and height.
Case 2, Adjust the height to be the new target size wile maintaining the correct aspect ratio.
Any help would be grand. Also currently I do not have cacheing in place for the UI to use but that will come with time (maybe). Currently the system operates solely from the database with no dependance on the file system and I'm trying to keep it that way hence why I'm storing the thumbs in the database.
Thanks,
Tim