顯示廣告
隱藏 ✕
看板 Farland
作者 Farland (法蘭多)
標題 [ASP.NET] 縮小圖片大小
時間 2013年03月25日 Mon. AM 11:19:59


由於呈現端只需要128x128大小的圖片
而User在上傳的時候才不會鳥你那麼多
因此我就自己在Server Side把圖片縮小啦

Code Snippet:
    ''' <summary>
    ''' 將小於指定長寬的圖片轉成指定的長寬
    ''' </summary>
    ''' <param name="buffer">圖檔binary</param>
    ''' <param name="height">指定的高度</param>
    ''' <param name="width">指定的寬度</param>
    ''' <param name="imgFormat">圖片格式</param>
    ''' <returns>binary</returns>
    ''' <remarks></remarks>
    Private Function ConvertImage(ByVal buffer As Byte(), ByVal height As Integer, ByVal width As Integer, ByVal imgFormat As Drawing.Imaging.ImageFormat) As Byte()
        Try
            Dim img As Drawing.Image = Drawing.Image.FromStream(New System.IO.MemoryStream(buffer))

            '當長寬皆小於指定的長寬就不需要縮
            If img.Height <= height AndAlso img.Width <= width Then Return buffer
            Dim newHeight As Integer = If(img.Height < height, img.Height, height)
            Dim newWidth As Integer = If(img.Width < width, img.Width, width)

            Dim bitmap As New Drawing.Bitmap(newHeight, newWidth)
            Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(bitmap)

            '設為高品質,盡量讓圖片不失真
            g.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
            g.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
            g.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality

            g.DrawImage(img, New Drawing.Rectangle(0, 0, newHeight, newWidth))

            Dim ms As New IO.MemoryStream
            bitmap.Save(ms, imgFormat)

            Dim result As Byte() = ms.ToArray()

            img.Dispose()
            bitmap.Dispose()
            g.Dispose()
            ms.Dispose()

            Return result
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

--
※ 作者: Farland 時間: 2013-03-25 11:19:59
※ 編輯: Farland 時間: 2013-03-25 11:31:14
※ 看板: Farland 文章推薦值: 0 目前人氣: 0 累積人氣: 807 
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇