Reputation: 326
I am trying to resize image, my current image dimensions are (1800*1197)
and having file size = 305kb
, when i tried to reduce dimensions to (1200*900)
and save the file its size drastically increases to 1.75mb
.
I have called the below method resizeImage like:
Image MainImage = resizeImage(BaseImage, 1200, 900, false);
I am using the function to resize image as below:
public static Bitmap resizeImage(Image imgToResize, int lnWidth, int lnHeight, bool _FixHeightWidth)
{
System.Drawing.Bitmap bmpOut = null;
Graphics g;
try
{
Bitmap loBMP = new Bitmap(imgToResize);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
//*** If the image is smaller than a thumbnail just return it
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight && _FixHeightWidth == false)
{
bmpOut = new Bitmap(loBMP.Width, loBMP.Height);
g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.FillRectangle(Brushes.White, 0, 0, loBMP.Width, loBMP.Height);
g.DrawImage(loBMP, 0, 0, loBMP.Width, loBMP.Height);
loBMP.Dispose();
return bmpOut;
}
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}
if (_FixHeightWidth == true)
{
lnNewHeight = lnHeight;
lnNewWidth = lnWidth;
}
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
After this conversion success i simply save the file, but instead of decreasing, it increases file size. so i just wanted the file size either should remain same(305kb) or reduce it accordingly.
Note: I just want suggestions on how to work with this kind of situation, also some explanation would be great that what thing is causing this issue, also if any other solutions are there.
Update: File format is '.jpg'
MainImage.Save(Path.Combine(pathForSaving, fileName));
Upvotes: 0
Views: 994
Reputation: 171
I supose you are using an original ImageFormat of file to write the new image... If the original image is a bitmap, the result format will be to, only change the extension... You need to set an Encoder. Also, you can try to change the IterpolationMode to a medium-low quality or the format of the file to PNG format is better for internet use...
Upvotes: 1