I have a function that takes in a byte array of image data and then resizes it so its height and or width are around 200px max.
The function successfully reduces the size of the image (in terms of dimensions), but the size of the file gets drastically increased.
Example: Resized an image that is originally 32.2KB with dimensions of 828x251. The output is an image that is 374KB with dimensions of 577x200.
Below is the function being used:
public static string resizeImage(string imgToResize)
{
try
{
string image_info = imgToResize.Split(',')[0];
MemoryStream ms = new MemoryStream(Convert.FromBase64String(imgToResize.Split(',')[1]));
System.Drawing.Image converted_image = System.Drawing.Image.FromStream(ms);
int original_width = converted_image.Width;
int original_height = converted_image.Height;
// Figure out the ratio
double ratioX = (double) original_width / (double) original_height;
double ratioY = (double) original_height / (double) original_width;
// use whichever multiplier is smaller
double ratio = ratioX < ratioY ? ratioX : ratioY;
int new_height = 0;// Convert.ToInt32(original_height * ratio);
int new_width = 0;// Convert.ToInt32(original_width * ratio);
// now we can get the new height and width
if (original_width <= original_height)
{
new_width = 200;
new_height = Convert.ToInt32((decimal)new_width / (decimal)ratio);
}
else {
new_width = Convert.ToInt32((decimal)original_width * (1-(decimal)ratio));
new_height = 200;
}
Size image_size = new Size(new_width, new_height);
System.Drawing.Image new_image = (System.Drawing.Image)(new Bitmap(converted_image, image_size));
using (MemoryStream m = new MemoryStream())
{
new_image.Save(m, ImageFormat.Bmp);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return image_info + "," + base64String;
}
}
catch (Exception ex) {
ErrorSignal.FromCurrentContext().Raise(ex);
}
return "";
}
Can anyone explain why the file size is getting drastically increased from this reduction in dimensions and how to prevent it (or actually reduce the size of the file in addition to reducing its dimensions)?
You're saving it as a .bmp, which will have a much larger filesize.
Change the line new_image.Save(m, ImageFormat.Bmp);
to new_image.Save(m, ImageFormat.Png);
or new_image.Save(m);
, which will save it as a .png instead of an uncompressed .bmp (the latter chooses the .png format by default).
See Image.Save docs for more info.