我必须在我的项目中实现此功能,而我添加此功能时我在新位图附近出错

时间:2016-06-06 09:47:23

标签: asp.net vb.net

Public Shared Function ScaleImage(image As System.Drawing.Image, maxHeight As Integer) As System.Drawing.Image
    Dim ratio = CDbl(maxHeight) / image.Height
    Dim newWidth = CInt(Math.Truncate(image.Width * ratio))
    Dim newHeight = CInt(Math.Truncate(image.Height * ratio))
    Dim newImage = **New Bitmap(newWidth, newHeight)**
    Using g = Graphics.FromImage(newImage)
        g.DrawImage(image, 0, 0, newWidth, newHeight)
    End Using
    Return newImage
End Function

1 个答案:

答案 0 :(得分:1)

您目前正在将所有内容声明为Object,编译器不知道您想要哪种类型的变量。

您应始终确保在声明中包含该内容,以减少此类并发症的可能性。这就是As关键字的用途。

Dim ratio As Double = CDbl(maxHeight) / image.Height
Dim newWidth As Integer = CInt(Math.Truncate(image.Width * ratio))
Dim newHeight As Integer = CInt(Math.Truncate(image.Height * ratio))
Dim newImage As New Bitmap(newWidth, newHeight)
Using g As Graphics = Graphics.FromImage(newImage)
    g.DrawImage(image, 0, 0, newWidth, newHeight)
End Using
Return newImage