[VB] 图片等比例缩小方法

摘要:[VB] 图片等比例缩小方法


将图片等比例缩小的方法


'设定图片长宽
    Public Sub setImageWH()
        Try
            '图片位置
            Dim FilePath As String = "~/Images/Img.png"
            '取得图片真实路径
            Dim realPath As String = HttpContext.Current.Request.MapPath(FilePath)
            '
            Dim ImgDw As System.Drawing.Image = System.Drawing.Image.FromFile(realPath)
            '取得缩图后的长宽
            Dim imgSize() As Integer = getThumbnailImageScale(120, 100, ImgDw.Width, ImgDw.Height)
            ImgDw.Dispose()
            '设定图片长宽
            imgTest.Width = imgSize(0)
            imgTest.Height = imgSize(1)

        Catch ex As Exception
        End Try
    End Sub


    '保存时使用
    Private Sub imgresize(ByVal width As Integer, ByVal height As Integer, ByVal saveurl As String, ByVal filebytes As Byte(), ByVal filelength As Integer)
        Dim ms As MemoryStream = New MemoryStream
        ms.Write(filebytes, 0, filelength)
        ms.Flush()
        Dim img1 As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
        If img1.Height > height Or img1.Width > width Then
            '是否有超高or宽
            Dim newimg As System.Drawing.Image
            Dim thumbnailScale As Integer() = getThumbnailImageScale(width, height, img1.Width, img1.Height)


            '算出原图长宽比
            newimg = img1.GetThumbnailImage(thumbnailScale(0), thumbnailScale(1), Nothing, IntPtr.Zero)
            '释放资源
            newimg.Save(saveurl)
            newimg.Dispose()
            img1.Dispose()
            ms.Close()
        End If
    End Sub

    '带入限制范围长宽跟原图片长宽
    Private Function getThumbnailImageScale(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal oldWidth As Integer, ByVal oldHeight As Integer) As Integer()
        Dim result() As Integer = New Integer() {0, 0}
        Dim widthDividend As Single, heightDividend As Single, commonDividend As Single
        widthDividend = oldWidth / maxWidth
        heightDividend = oldHeight / maxHeight
        If (heightDividend > widthDividend) Then
            commonDividend = heightDividend
        Else
            commonDividend = widthDividend
        End If
        result(0) = CType((oldWidth / commonDividend), Integer)
        result(1) = CType((oldHeight / commonDividend), Integer)
        Return result
    End Function



以上文章叙述如有错误及观念不正确,请不吝啬指教
如有侵权内容也请您与我反应~谢谢您 :)

原文:大专栏  [VB] 图片等比例缩小方法


猜你喜欢

转载自www.cnblogs.com/chinatrump/p/11514329.html
VB