调整.net中的图像和宽高比?

时间:2010-07-07 18:41:16

标签: .net vb.net

我正在使用一张320 x 240张照片的网络摄像头。这种类型为图片提供了“风景”外观,我需要将图片重新调整为169 X 225“肖像”图片。它用于徽章计划。无论如何,当我重新调整图片大小时,由于宽高比的不同,它们会全部被碾碎。有没有办法同时重新调整图像大小和宽高比?这会被视为裁剪还是调整大小?我对从哪里开始有点困惑。我主要使用VB,但如果有人在C#中有一个很好的例子,那么就花时间来转换它。谢谢

3 个答案:

答案 0 :(得分:3)

改变纵横比和裁剪是一回事。您可以像这样计算新的纵向尺寸:(基于标准3 x 5照片尺寸的比率)

Double aspectRatio = 3.0 / 5.0
Int newHeight = actualHeight ' Use full height
Int newWidth = actualWidth * aspectRatio

你想要一个中心裁剪,所以你必须像这样计算:

Int cropY = 0 ' Use full height
Int cropX = actualWidth / 2.0 - newWidth / 2.0

System.Drawing中的Bitmap对象有一个Clone method,它接受​​一个裁剪矩形作为参数。 Graphics对象有一个DrawImage method,您可以使用它来同时调整图像大小和裁剪图像。

答案 1 :(得分:2)

你有两个选择。您可以裁剪,因为最终尺寸非常接近原始尺寸,或者您可以裁剪和调整大小。如果您裁剪然后调整大小,您将需要裁剪为180x240以获得正确的宽高比;当你将结果调整为169x225时,不会有任何失真。

这是我在VB.NET中用来描述裁剪的快速链接:http://www.nerdydork.com/crop-an-image-bitmap-in-c-or-vbnet.html

答案 2 :(得分:0)

http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-rotate

private  Bitmap rotateImage(Bitmap b, float  angle)
{
//create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image
g.TranslateTransform((float)b.Width/2, (float)b.Height / 2);
//rotate
g.RotateTransform(angle);
//move image back
g.TranslateTransform(-(float)b.Width/2,-(float)b.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(b, new Point(0, 0));
return returnBitmap;
}"




private  static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);

if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();

return (Image)b;
}



private  static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (Image)(bmpCrop);
}