一樣,最近作專案有用到

用途是於上傳圖片的同時進行縮圖處理

如此日後可以減少圖片下載時所需的頻寬(因為圖檔被縮小了)

也可以強制圖片必須為長寬多少內~(若使用者本身不懂縮圖,這個函數會自動幫忙處理)

 

分享一下原始碼跟方法

‘原始碼開始

 

  ’縮圖


    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


    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

 

‘原始碼結束