C# 如何调整图像大小并保持纵横比?
我正在尝试调整图片大小,使其适合640x640大小并保持纵横比 例如,如果这是原始图片: 我想以这样的方式调整大小:基本上保持纵横比,图像总是在中间,并且保持纵横比,其余的空间保持白色 我曾尝试用C语言编写一个程序,其中包含以下代码:C# 如何调整图像大小并保持纵横比?,c#,image,image-resizing,C#,Image,Image Resizing,我正在尝试调整图片大小,使其适合640x640大小并保持纵横比 例如,如果这是原始图片: 我想以这样的方式调整大小:基本上保持纵横比,图像总是在中间,并且保持纵横比,其余的空间保持白色 我曾尝试用C语言编写一个程序,其中包含以下代码: Bitmap originalImage, resizedImage; try { using (FileStream fs = new FileStream(textBox1.Te
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);
}
但是它不能按我需要的方式工作。你能给图像标签添加最大宽度:100%吗。并使用css定义父标记的固定宽度。希望这样应该可以工作,不需要为同样的代码编写c代码
Eg. <figure > <img src="" > </figure>
Css
Figure{ width:600px }
Img { max-width: 100%}
设W,H为图像的大小。设s=maxW,H。然后要将图像大小调整为w,H=640*w/s,640*H/s,其中/表示整数除法。请注意,如果我听起来像个傻瓜,我们很抱歉,但我不太懂CSS。你介意解释一下如何使用它,以及如何使用它调整多个图像的大小吗?@jmelosegui谢谢你的链接,但我真的不懂jQuery。这就是为什么我要在C中取得成功。先生,你真的应该得到一枚奖牌。您不仅解释了它是如何完成的,而且还提供了代码。我喜欢你跳出框框思考的方式。非常感谢@user5204184这里最大的三点是:1.首先在纸上解决问题;2.除非绝对必要,否则不要逐案推理;3.如果你的问题只涉及整数,而且所有结果都应该是整数,尽量避免将浮点数混入其中。非常感谢你的建议。我非常感激。下次尝试编写代码时,我一定会记住这一点。
var sourcePath = textBox1.Text;
var destinationSize = 640;
using (var destinationImage = new Bitmap(destinationSize, destinationSize))
{
using (var graphics = Graphics.FromImage(destinationImage))
{
graphics.Clear(Color.White);
using (var sourceImage = new Bitmap(sourcePath))
{
var s = Math.Max(sourceImage.Width, sourceImage.Height);
var w = destinationSize * sourceImage.Width / s;
var h = destinationSize * sourceImage.Height / s;
var x = (destinationSize - w) / 2;
var y = (destinationSize - h) / 2;
// Use alpha blending in case the source image has transparencies.
graphics.CompositingMode = CompositingMode.SourceOver;
// Use high quality compositing and interpolation.
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(sourceImage, x, y, w, h);
}
}
destinationImage.Save(...);
}