如何为图像大小调整代码添加约束?即不大于165x146

时间:2012-02-15 19:25:08

标签: vb.net image-resizing

如何为图像大小调整代码添加约束?我希望图像不大于165x146。当图像为525x610

时,以下代码不保留约束
        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

1 个答案:

答案 0 :(得分:1)

我认为你想保持图像的宽高比?如果是这样,这种方法可能是合适的;你需要将宽度和高度乘以你得到的比率。

'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))

编辑:可能需要明确地将新的高度和宽度转换为整数