gpt4 book ai didi

c# - 如何调整图像大小并保持纵横比?

转载 作者:行者123 更新时间:2023-12-05 07:54:03 26 4
gpt4 key购买 nike

我正在尝试调整图片大小以适合 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);
}

但它没有按照我需要的方式工作。

最佳答案

(W, H)是你的形象的大小。让s = max(W, H) .然后您想将图像调整为 (w, h) = (640 * W / s, 640 * H / s)其中 /表示整数除法。请注意,我们有 w <= 640h <= 640max(w, h) = 640 .

图像在新 (640, 640) 中的水平和垂直偏移量图片是 x = (640 - W) / 2y = (640 - H) / 2 , 分别。

您可以通过创建一个新的 (640, 640) 来完成所有这些空白的白色图像,然后将当前图像绘制到矩形 (x, y, w, h) .

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(...);
}

关于c# - 如何调整图像大小并保持纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com