作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试调整图片大小以适合 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 <= 640
和 h <= 640
和 max(w, h) = 640
.
图像在新 (640, 640)
中的水平和垂直偏移量图片是 x = (640 - W) / 2
和 y = (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/
我有一张 table 。我希望它的数据垂直和水平居中。 我使用了 align="center"valign="middle" ,但它没有用。
我是一名优秀的程序员,十分优秀!