I have an MVC application where you can upload a picture and it gets resized to max. 50KB. I do the resizing in a while loop but the problem is when i decrease the width and height of the picture the file size increases. At a certain point the size gets smaller but at the cost of quality
Request.InputStream.Position = 0;
string Data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var Base64 = Data.Split(',')[1];
var BitmapBytes = Convert.FromBase64String(Base64);
var Bmp = new Bitmap(new MemoryStream(BitmapBytes));
while (BitmapBytes.Length > 51200)
{
int Schritte = 20; //I tested here also with 300
int maxWidth = Bmp.Width;
maxWidth = maxWidth - Schritte;
int maxHeight = Bmp.Height;
maxHeight = maxHeight - Schritte;
Bmp = ScaleImage(Bmp, maxWidth, maxHeight);
var base64 = ReturnImageAsBase64(Bmp);
BitmapBytes = Convert.FromBase64String(base64);
}
The Code to resize:
public static Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight));
}
return newImage;
}
I start with a Size of 66964 Bytes. After the first turn in the loop its 85151 Bytes and this although the width was reduced by 300 pixel and the height by 420 pixel.