The file type in this case is jpg
private void beginOperationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (files.Length > 0)
{
backgroundWorker1.RunWorkerAsync();
}
}
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
if (newWidth >= 0 && newHeight >= 0)
{
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
return null;
}
}
Then
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
int counter = 0;
int percentage = 0;
foreach (string file in files)
{
Bitmap bmp1 = new Bitmap(ResizeImage(file, 512, 512));
string resizedfilename = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(file) "_resized.jpg");
bmp1.Save(resizedfilename);
bmp1.Dispose();
counter ;
percentage = counter * 100 / files.Length;
worker.ReportProgress(percentage);
}
}
catch(Exception err)
{
}
}
The original image jpg size on the hard disk is Width 536 and Height 589
The resize image on the hard disk is Width 512 Height 536
Why the resized image Height is 536 ?
and why the size on the hard disk of the resized image is 600 KB while the original image size is only 130 KB ?
CodePudding user response:
I think your aspect ratio less than and greater than are backwards. If the image is 'landscape' (width > height), then the aspect ration will be positive (because you are doing width
/ height
). If it's 'portrait', it will be negative. But you have them the other way around.