Vb.net 如何向图像大小调整代码添加约束?i、 e.不大于165x146
如何向图像大小调整代码添加约束?我希望图像不大于165x146。当图像为525x610时,以下代码不具有约束Vb.net 如何向图像大小调整代码添加约束?i、 e.不大于165x146,vb.net,image-resizing,Vb.net,Image Resizing,如何向图像大小调整代码添加约束?我希望图像不大于165x146。当图像为525x610时,以下代码不具有约束 intWidth = 165 '*** Fix Width ***' intHeight = 146 '*** Fix Width ***' If objGraphic.Width > intWidth Then Dim ratio As Double = objGraphic.Heig
intWidth = 165 '*** Fix Width ***'
intHeight = 146 '*** Fix Width ***'
If objGraphic.Width > intWidth Then
Dim ratio As Double = objGraphic.Height / objGraphic.Width
intHeight = ratio * intWidth
objBitmap = New Bitmap(objGraphic, intWidth, intHeight)
ElseIf objGraphic.Height > intHeight Then
Dim ratio As Double = objGraphic.Width / objGraphic.Height
intWidth = ratio * intHeight
objBitmap = New Bitmap(objGraphic, intWidth, intHeight)
Else
objBitmap = New Bitmap(objGraphic)
End If
我想你想保持图像的纵横比吗?如果是这样,这种方法可能是合适的;您需要将宽度和高度乘以您获得的比率
'define max size of image
intWidth = 165
intHeight = 146
'if the width/height is larger than the max, determine the appropriate ratio
Dim widthRatio as Double = Math.Min(1, intWidth / objGraphic.Width)
Dim heightRatio as Double = Math.Min(1, intHeight / objGraphic.Height)
'take the smaller of the two ratios as the one we will use to resize the image
Dim ratio as Double = Math.Min(widthRatio, heightRatio)
'apply the ratio to both the width and the height to ensure the aspect is maintained
objBitmap = New Bitmap(objGraphic, CInt(objGraphic.Width * ratio), CInt(objGraphic.Height * ratio))
编辑:可能需要显式地将新的高度和宽度转换为int,该值将返回525x610,因为比率将为1。如果
objGraphic.width>intWidth
,intWidth/objGraphic.width
将始终小于1。身高也一样。由于我们执行Min(1,[一些数字小于或等于1])
,它将小于或等于1。在您的示例中,widthRatio=Min(1,0.314)=0.314
,heightRatio=Min(1,0.239)=0.239
,以及ratio=Min(0.314,0.239)=0.239
。您的新宽度将是525*.239=125
,您的高度将是610*.239=146
为什么ratio=MIN(0.314,0.239)=0.239
为什么不选择ratio=MAX(0.314,0.239)=0.239
?您的意思是MAX(0.314,0.239)=0.314
?不管怎样,那都是不正确的。。。您希望将其限制为165*146的最大大小。您有原始尺寸与其各自尺寸的比率。如果选择较大的比率(widthRatio),则新的宽度将正好为165,但新的高度将大于146。因此,要约束到最大大小并保持图像的纵横比,必须使用较小的纵横比。我在许多处理图像的应用程序中使用类似的代码。我的建议是逐步完成并测试它。