我想调整图片大小使其符合 640x640 的尺寸,并保持宽高比。例如,如果这是原始图片:http://i.imgur.com/WEMCSyd.jpg我想要按照以下方式调整大小:http://i.imgur.com/K2BalOm.jpg以保持纵横比(基本上,图像总是位于中间,保持宽高比,其余空间保留为白色)。我尝试编写了一个 C#程序,其中包含以下代码:
但是它不符合我的需求。
Bitmap originalImage, resizedImage;
try
{
using (FileStream fs = new FileStream(textBox1.Text, System.IO.FileMode.Open))
{
originalImage = new Bitmap(fs);
}
int imgHeight = 640;
int imgWidth = 640;
if (originalImage.Height == originalImage.Width)
{
resizedImage = new Bitmap(originalImage, imgHeight, imgWidth);
}
else
{
float aspect = originalImage.Width / (float)originalImage.Height;
int newHeight;
int newWidth;
newWidth = (int)(imgWidth / aspect);
newHeight = (int)(newWidth / aspect);
if (newWidth > imgWidth || newHeight > imgHeight)
{
if (newWidth > newHeight)
{
newWidth = newHeight;
newHeight = (int)(newWidth / aspect);
}
else
{
newHeight = newWidth;
newWidth = (int)(newHeight / aspect);
}
}
resizedImage = new Bitmap(originalImage, newWidth, newHeight);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
但是它不符合我的需求。