调整图像大小 - 错误GDI +

时间:2015-05-01 00:14:25

标签: asp.net vb.net image

我试图调整图片大小但是当我到达这行代码时: resized.Save(physicalPath,Drawing.Imaging.ImageFormat.Jpeg)

它抛出错误:GDI +中发生了一般错误。 是否有人在???

之前遇到了这个错误

这是我的完整代码:

Dim original As Image = Image.FromFile(physicalPath)
        Dim resized As Image = ResizeImage(original, New Size(100, 100))
        Dim memStream As MemoryStream = New MemoryStream()
        resized.Save(physicalPath, Drawing.Imaging.ImageFormat.Jpeg)

调整大小的功能:

 'The method takes two mandatory parameters: the image to be resized and the new size it is to be resized to. 
    'An optional third parameter specifies whether to preserve the image's original aspect ratio
    Public Shared Function ResizeImage(ByVal image As Image, _
ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image

        'If we are not going to preserve the aspect ratio of the original image, then we simply set the height and width of the new image accordingly. 
        'However, if we do wish to preserve the aspect ratio, then the situation is a little more complex: Firstly, 
        'we need to calculate the percentage difference,in each axis (height and width), between the original image and the desired size. 
        'Then we use whichever difference is the smaller to calculate the new height and width of the new image:
        Dim newWidth As Integer
        Dim newHeight As Integer
        If preserveAspectRatio Then
            Dim originalWidth As Integer = image.Width
            Dim originalHeight As Integer = image.Height
            Dim percentWidth As Single = CSng(Size.Width) / CSng(originalWidth)
            Dim percentHeight As Single = CSng(Size.Height) / CSng(originalHeight)
            Dim percent As Single = If(percentHeight < percentWidth, percentHeight, percentWidth)
            newWidth = CInt(originalWidth * percent)
            newHeight = CInt(originalHeight * percent)
        Else
            newWidth = Size.Width
            newHeight = Size.Height
        End If

        'Next, we create a blank bitmap using our new dimensions
        Dim newImage As Image = New Bitmap(newWidth, newHeight)
        'Finally, we use the graphics handle of the new bitmap to draw the original image onto our new bitmap and return it:

        Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
            graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
        End Using
        Return newImage
    End Function

1 个答案:

答案 0 :(得分:0)

使用DrawImage方法的this重载。使用矩形来定义区域。

graphicsHandle.DrawImage(image, New Rectangle(0, 0, newWidth, newHeight))