[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

 

 


以上文章敘述如有錯誤及觀念不正確,請不吝嗇指教
如有侵權內容也請您與我反應~謝謝您 :)